如何在特定 div 中强制运行 JS 函数

我正在尝试用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);

}


慕哥6287543
浏览 205回答 2
2回答

萧十郎

问题是您正在调用 .appendChild()bodyfunction LoadAllProducts() {&nbsp; &nbsp; var x = document.createElement("TABLE");&nbsp; &nbsp; x.setAttribute("id", "table");&nbsp; &nbsp; // Instead of document.body, use document.getElementById()&nbsp; &nbsp; document.getElementById("products-row").appendChild(x);&nbsp; &nbsp; var y = document.createElement("TBODY");&nbsp; &nbsp; y.setAttribute("id", "products");&nbsp; &nbsp; // ... like you were using here...&nbsp; &nbsp; document.getElementById("table").appendChild(y);}函数调用在HTML中的位置并不重要,都会引用当前页面的元素。document.bodybodydocument

守候你守候我

&nbsp;document.body.appendChild(x);显然是 document.body。该程序正在完全按照您的指示执行操作...将节附加到文档的正文。该程序不理解“含义”,例如“我把这个代码放在这里,所以我期望代码在这里输出”。JavaScript DOM 不是这样工作的。您必须指定输出的去向。如果你想让它出现在产品行中,你必须告诉它去那里document.getElementById("products-row").appendChild(x)在这种情况下,我们通过id获取元素“products-rows”,然后告诉代码“在这里附加我的输出x”。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript