简体   繁体   English

如何使用 Js 在 HTML BODY 中插入一个元素,然后使用 Js 选择相同的元素,然后向其中添加更多数据?

[英]How can i insert an element in the HTML BODY using Js then select the same element using Js and then append some more data into it?

I am trying to make a single page web app and i have different tabs example is unapproved tab .我正在尝试制作一个单页 Web 应用程序,并且我有不同的选项卡示例是unapproved tab when i click on this tab i prevent the default using action using js then i get the container element of the page当我单击此选项卡时,我会使用 js 阻止默认使用操作,然后我获取页面的容器元素

let container = document.getElementById('container');

i then insert a table in the container然后我在容器中插入一张表

container.innerHTML = `
        <table id="table" class="table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">First</th>
                    <th scope="col">Last</th>
                    <th scope="col">Handle</th>
                </tr>
            </thead>
            <tbody id="tablebody">

            </tbody>
        </table>
        `;

once that is done i fetch some data using ajax and insert then into the table body using js.完成后,我使用 ajax 获取一些数据,然后使用 js 插入到表体中。

     try {
        http.get('../includes/unapproved.inc.php')
            .then(res => {
                //check if the response if ok
                console.log(res);
                let rows = '';
                for (let i in res) {
                    rows += ` 
               <tr>
                    <td>${res[i].user_user_id} <td>
               <tr>
               `
                }
                tablebody.innerHTML = rows;
                console.log(table);

            });
    } catch (error) {
        console.log(error);

    }

But when i try to insert the data i get this error但是当我尝试插入数据时,我收到此错误

pages.js:51 Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
    at pages.js:51

i do not understand why i am getting this error yet i have already inserted the table in the DOM.我不明白为什么我会收到这个错误,但我已经在 DOM 中插入了表格。

below is the whole code下面是整个代码

import { FETCH } from "./fetch.js";

export class PAGES {
    constructor() {
        this.unapproved = document.getElementById('unapproved');
    }
    events() {
        this.unapproved.addEventListener('click', (e) => {
            e.preventDefault();
            this.unapprovedPage();

        })
    }
    unapprovedPage() {
        let container = document.getElementById('container');
        let table = document.getElementById('table');
        let tablebody = document.getElementById('tablebody');
        container.innerHTML = `
        <table id="table" class="table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">First</th>
                    <th scope="col">Last</th>
                    <th scope="col">Handle</th>
                </tr>
            </thead>
            <tbody id="tablebody">

            </tbody>
        </table>
        `;

        const http = new FETCH;

        try {
            http.get('../includes/unapproved.inc.php')
                .then(res => {
                    //check if the response if ok
                    console.log(res);
                    let rows = '';
                    for (let i in res) {
                        rows += ` 
                   <tr>
                        <td>${res[i].user_user_id} <td>
                   <tr>
                   `
                    }
                    tablebody.innerHTML = rows;
                    console.log(table);

                });
        } catch (error) {
            console.log(error);

        }
    }


}

You are selecting the #tablebody element before it is in the document.您在文档中之前选择了#tablebody元素。 So the result will always be null .所以结果总是null

First add the innerHTML content of the container element.首先添加容器元素的innerHTML内容。

container.innerHTML = `
<table id="table" class="table">
    <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">First</th>
            <th scope="col">Last</th>
            <th scope="col">Handle</th>
        </tr>
    </thead>
    <tbody id="tablebody">

    </tbody>
</table>
`;

And then select the element from the container using querySelector .然后使用querySelector从容器中选择元素。

let tablebody = container.querySelector('#tablebody');

Also, prevent using ID's when appending dynamic content and instead use classes.此外,在附加动态内容时避免使用 ID,而是使用类。 Your page will not work as expected when there is more than one element with the same ID is on the page.当页面上有多个具有相同 ID 的元素时,您的页面将无法按预期工作。

in the example below i have an funtion event that will listen for a button click then depending on the button clicked it will update the location.hash when location.hash is changed i have a funtion somewhere that will load the testdata page which has an empty table inside it and insert the page content in the main.page .在下面的示例中,我有一个函数事件,它将侦听按钮单击,然后根据单击的按钮更新location.hash,当 location.hash 更改时,我在某处有一个函数可以加载testdata页面在其中插入表格并将页面内容插入main.page this.unapprovedPage(); this.unapprovedPage(); function will then load some data from the server and feed the table that has now been loaded in the mainpage .然后函数将从服务器加载一些数据并提供现在已加载到主页中的表

Everything works well but the problem is that when i click the respective button clicked very fast i get the error below or when i click it for the first time but when i click it for the second time all works well and the data is feed into the table一切正常,但问题是当我点击相应的按钮时,点击速度非常快,我收到以下错误,或者当我第一次点击它时,但是当我第二次点击它时一切正常,数据被输入桌子

Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
at pages.js:47

How can i ensure that when the button is clicked the data is only feed into the table only once the the testdata page has been loaded?我如何确保单击按钮时数据仅在加载testdata页面后才馈入表格?

events() {
        this.unapproved.addEventListener('click', (e) => {
            console.log('i have been clicked');
            e.preventDefault();
            location.hash = "testdata";
            this.unapprovedPage();


        })
    }
    unapprovedPage() {
        let table = document.getElementById('table');
        const http = new FETCH;

        try {
            http.get('../includes/unapproved.inc.php')
                .then(res => {
                    //check if the response if ok
                    console.log(res);
                    let rows = '';
                    for (let i in res) {
                        rows += ` 
                   <tr>
                        <th scope="row">1</th>
                        <td>${res[i].user_user_id} </td>
                        <td>${res[i].user_user_id} </td>
                        <td>${res[i].user_user_id} </td>
                        <td>${res[i].user_user_id} </td>
                        <td>${res[i].user_user_id} </td>
                   </tr>
                   `
                    }
                    let tablebody = document.getElementById('tableBody');
                    tablebody.innerHTML = rows;
                    $(document).ready(function() {
                        $('#example').DataTable();
                    } );

                });
        } catch (error) {
            console.log(error);

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM