亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在特定 div 中強制運行 JS 函數

如何在特定 div 中強制運行 JS 函數

慕哥6287543 2022-08-04 10:34:44
我正在嘗試用js構建表,但我無法強制它在特定的div中構建,它總是在整個部分之外創建我的表。有什么辦法可以強迫它嗎?網頁:<section class="all-products" id="all-products">    <div class="container">        <div class="title-box">            <h2>Products</h2>        </div>        <div class="row" id=products-row">            <script>              LoadAllProducts();            </script>        </div>    </div></section>負載產品.js:function LoadAllProducts() {    var x = document.createElement("TABLE");    x.setAttribute("id", "table");    document.body.appendChild(x);    var y = document.createElement("TBODY");    y.setAttribute("id", "products");    document.getElementById("table").appendChild(y);}
查看完整描述

2 回答

?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

問題是您正在調用 .appendChild()body


function LoadAllProducts() {

    var x = document.createElement("TABLE");

    x.setAttribute("id", "table");

    // Instead of document.body, use document.getElementById()

    document.getElementById("products-row").appendChild(x);


    var y = document.createElement("TBODY");

    y.setAttribute("id", "products");

    // ... like you were using here...

    document.getElementById("table").appendChild(y);

}


函數調用在HTML中的位置并不重要,都會引用當前頁面的元素。document.bodybodydocument


查看完整回答
反對 回復 2022-08-04
?
守候你守候我

TA貢獻1802條經驗 獲得超10個贊

 document.body.appendChild(x);

顯然是 document.body。該程序正在完全按照您的指示執行操作...將節附加到文檔的正文。

該程序不理解“含義”,例如“我把這個代碼放在這里,所以我期望代碼在這里輸出”。JavaScript DOM 不是這樣工作的。您必須指定輸出的去向。

如果你想讓它出現在產品行中,你必須告訴它去那里

document.getElementById("products-row").appendChild(x)

在這種情況下,我們通過id獲取元素“products-rows”,然后告訴代碼“在這里附加我的輸出x”。


查看完整回答
反對 回復 2022-08-04
  • 2 回答
  • 0 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號