首页 > 解决方案 > 声明元素而不将它们放在函数内

问题描述

嗨,伙计们遇到了麻烦,当我在循环之外声明元素时,脚本最终被破坏了。我计划在几个函数中使用这些元素。尝试了很多次,但没有找到解决方案。在做猜测工作时破坏了几次项目。另外,如果有任何关于如何缩短它或让它更好地工作的想法,请给我一个提示:)

async function loadTable() {
    try {
        while(dpTable.firstChild) dpTable.removeChild(dpTable.firstChild);
        const result = await fetch('http://localhost:5000/users/student_data', { method: 'GET' });
        const table = await result.json();
        table.forEach((res) => {
            //Create Table elements and then load results into the elements
            const tr = document.createElement('tr');
            const studentNo = document.createElement('td');
            const name = document.createElement('td');
            const surname = document.createElement('td');
            const date_joined = document.createElement('td');
            const fees_paid = document.createElement('td');
            const fees_owing = document.createElement('td');
            const is_owing = document.createElement('td');
            const trash_btn = document.createElement('button');
            const trash_Icon = document.createElement('i');
            
            tr.id = 'Content';
            studentNo.id = res.id;
            name.id = 'fname';
            surname.id = 'lname';
            fees_paid.id = 'amount_paid';
            fees_owing.id = 'amount_owing';
            is_owing.id = 'debt';


            //Enter the data from the response
            studentNo.innerText = res.id;
            name.innerText = res.fname;
            surname.innerText = res.lname;
            fees_paid.innerText = res.amount_paid;
            fees_owing.innerText = res.amount_owing;
            date_joined.innerText = res.date_joined;
            is_owing.innerText = res.is_owing;
            trash_btn.innerText = 'Delete';

            //Add Classes for elements
            studentNo.classList.add('trContent');
            name.classList.add('trContent');
            surname.classList.add('trContent');
            fees_paid.classList.add('trContent');
            fees_owing.classList.add('trContent');
            date_joined.classList.add('trContent');
            is_owing.classList.add('trContent');
            trash_Icon.classList.add('fas');
            trash_Icon.classList.add('fa-trash');
            trash_Icon.classList.add('trash-btn');

            //Append table row elements to main table
            tr.append(studentNo);
            tr.append(name);
            tr.append(surname);
            tr.append(fees_paid);
            tr.append(fees_owing);
            tr.append(date_joined);
            tr.append(is_owing);
            tr.append(trash_btn);

            //Event Listeners
            trash_btn.addEventListener('click', async (e) => {
                if (window.confirm('Delete')) {
                    console.log('trash icon clicked');
                    const jsonReq = {};
                    jsonReq.id = res.id;
                    const result = await fetch('http://localhost:5000/users/student_data', {
                        method: 'DELETE',
                        headers: { 'content-type': 'application/json' },
                        body: JSON.stringify(jsonReq),
                    });

                    alert('Deleted Record');
                    window.location.reload();
                }
            });

            //Append the table as a child to the main element
            dpTable.appendChild(tr);
        });
    } catch (e) {
        console.log(`Cant load List ${e}`);
    }
}

标签: javascripthtml

解决方案


这很可能是因为您将它们声明为const这意味着它们不应该被重写 - 但是您将它们放在一个循环中重新分配它们并因此导致错误。let在这种情况下,您可以改用

async function loadTable() {
    try {
        while(dpTable.firstChild) dpTable.removeChild(dpTable.firstChild);
        const result = await fetch('http://localhost:5000/users/student_data', { method: 'GET' });
        const table = await result.json();
        let tr, studentNo, name, surname, date_joined, fees_paid, fees_owing, is_owing, trash_btn, trash_Icon
        table.forEach((res) => {
            //Create Table elements and then load results into the elements
            tr = document.createElement('tr');
            studentNo = document.createElement('td');
            name = document.createElement('td');
            surname = document.createElement('td');
            date_joined = document.createElement('td');
            fees_paid = document.createElement('td');
            fees_owing = document.createElement('td');
            is_owing = document.createElement('td');
            trash_btn = document.createElement('button');
            trash_Icon = document.createElement('i');
            
            tr.id = 'Content';
            studentNo.id = res.id;
            name.id = 'fname';
            surname.id = 'lname';
            fees_paid.id = 'amount_paid';
            fees_owing.id = 'amount_owing';
            is_owing.id = 'debt';


            //Enter the data from the response
            studentNo.innerText = res.id;
            name.innerText = res.fname;
            surname.innerText = res.lname;
            fees_paid.innerText = res.amount_paid;
            fees_owing.innerText = res.amount_owing;
            date_joined.innerText = res.date_joined;
            is_owing.innerText = res.is_owing;
            trash_btn.innerText = 'Delete';

            //Add Classes for elements
            studentNo.classList.add('trContent');
            name.classList.add('trContent');
            surname.classList.add('trContent');
            fees_paid.classList.add('trContent');
            fees_owing.classList.add('trContent');
            date_joined.classList.add('trContent');
            is_owing.classList.add('trContent');
            trash_Icon.classList.add('fas');
            trash_Icon.classList.add('fa-trash');
            trash_Icon.classList.add('trash-btn');

            //Append table row elements to main table
            tr.append(studentNo);
            tr.append(name);
            tr.append(surname);
            tr.append(fees_paid);
            tr.append(fees_owing);
            tr.append(date_joined);
            tr.append(is_owing);
            tr.append(trash_btn);

            //Event Listeners
            trash_btn.addEventListener('click', async (e) => {
                if (window.confirm('Delete')) {
                    console.log('trash icon clicked');
                    const jsonReq = {};
                    jsonReq.id = res.id;
                    const result = await fetch('http://localhost:5000/users/student_data', {
                        method: 'DELETE',
                        headers: { 'content-type': 'application/json' },
                        body: JSON.stringify(jsonReq),
                    });

                    alert('Deleted Record');
                    window.location.reload();
                }
            });

            //Append the table as a child to the main element
            dpTable.appendChild(tr);
        });
    } catch (e) {
        console.log(`Cant load List ${e}`);
    }
}

推荐阅读