簡體   English   中英

無法獲取通過JavaScript添加的HTML元素

[英]Cannot fetch HTML element added via JavaScript

如標題所示,我在訪問添加有JavaScript的HTML元素時遇到了麻煩。 我嘗試使用JavaScript添加HTML div后,使用document.getElementById('sampleID')來獲取DOM元素。 但是,HTML源代碼無法反映所做的更改,因此我實際上無法獲取新元素。

該應用程序與待辦事項列表非常相似,但是跟蹤應用程序而不是任務。 提交的每個應用程序的div中都包含一個復選框,並且POST請求仍然通過,因此從數據庫中刪除了該應用程序,但是直到刷新后它才會反映在頁面中。

我偶然發現的唯一相關概念是JavaScript的MutationObserver接口,該接口似乎不允許訪問添加的元素。

所有建議表示贊賞!

$('#applicationDelete').submit(function(event) {
    event.preventDefault(); // Stops browser from navigating away from page
    var names = [];
    $(":checkbox").each(function () {
        var isChecked = $(this).is(":checked");
        if (isChecked) {
            names.push($(this).attr("class"));
        }
    });
    var data = { names: names }
    console.log('Data: ' + names);
    $.ajax({
        type: 'POST',
        contentType: 'application/json',
        url: window.location + 'applications/delete',
        data: JSON.stringify(data),
        dataType: 'json',
        success: function(res) {
            if (res.response == 'success') {
                var application;
                for (i in names) {
                    application = document.getElementById(names[i]);
                    application.parentNode.removeChild(application);
                }
            }
        }
    });
});

編輯:

function addApplication(application) {
    const container = document.getElementsByClassName('applicationDelete')[0];
    const appWrap = document.createElement('div');
    appWrap.classList.add('application-wrapper');

    // ADDED THIS LINE THANKS TO SUGGESTIONS!
    appWrap.id = application.company;

    const checkbox = document.createElement('div')
    checkbox.classList.add('checkbox');
    const check = document.createElement('input');
    check.type = 'checkbox';
    check.classList.add(application.company);
    const app = document.createElement('div')
    app.classList.add('application');

    checkbox.appendChild(check);
    appWrap.appendChild(checkbox);
    appWrap.appendChild(app);
    container.insertBefore(appWrap, container.childNodes[3]);

    app.innerHTML = '\
    Company: ' + application.company + '<br>\
    Position: ' + application.position + '<br>\
    Experience: ' + application.experience + '<br>\
    Source: ' + application.source + '<br>';

}

道歉的意大利面條代碼! 我確信我對類和ID的使用與正確的編碼約定相去甚遠,但是你們仍然設法找到我的錯誤(甚至沒有看到addApplication方法)。 謝謝!

您正在使用此方法將類名稱添加到名稱數組。

names.push($(this).attr("class"));

並通過id檢索元素。

application = document.getElementById(names[i]);

您應該將id存儲在名稱數組中(我也會為數組選擇其他名稱,這建議您存儲名稱)。

 names.push($(this).attr("id"));

或使用以下任一方法獲取元素。

document.getElementsByClassName(names[i]); //returns array

document.querySelector('.' + names[i]); //returns dom element

$('.' + names[i]); //returns jQuery object.

由於您使用的是jQuery,因此建議您使用jQuery解決方案。

isChecked檢查下,您將元素的class屬性推送到names數組:

names.push($(this).attr("class"));

這意味着您的names數組由可以在DOM中找到的classes組成,但是您稍后會查找ID 最簡單的解決方法是交換document.getElementById(names[i]); 對於.querySelector()方法:

document.querySelector(names[i]);
// or via jQuery:
$(`.${names[i]}`)

☝️但是只有在您可以確保您的類唯一的情況下(因為querySelector()找到與傳遞的查詢選擇器匹配的第一個元素)。

但是,一個更優雅的解決方案是使用 ID而不是類,因為HTML規范要求它們從一開始就必須是唯一的(這將使您沒有編寫或生成重復的類的故障安全保護)。 因此,鑒於您所有復選框現在都具有唯一的ID,請執行以下操作:

names.push($(this).attr("id"));
// now you can look for ID-s again!
document.getElementById(names[i]);
// Or a shortcut via jQuery (saving the extra variable):
application.parentNode.removeChild($(`#${names[i]}`));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM