无法获取通过JavaScript添加的HTML元素

问题描述 投票:2回答:2

正如标题所述,我无法访问使用JavaScript添加的HTML元素。我在使用JavaScript添加HTML div后尝试使用document.getElementById('sampleID')获取DOM元素。但是,HTML源代码并不反映所做的更改,因此我无法实际获取新元素。

该应用程序与ToDo列表非常相似,但跟踪应用程序而不是任务。每个提交的应用程序的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方法)。谢谢!

javascript html mutation-observers
2个回答
0
投票

你正在使用这个名字数组来输入类名。

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

并通过id检索元素。

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

你应该将id存储在names数组中(我会为数组选择不同的名称,它建议你存储名称)。

 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解决方案。


0
投票

isChecked检查下,你将元素的class属性推送到names数组:

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

这意味着你的names数组包含可以在DOM中找到的classes,但是你后来寻找IDs。最简单的解决方法是将document.getElementById(names[i]);换成.querySelector()方法:

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

☝️但只有当你可以确保你的类是唯一的时候才会这样(因为querySelector()找到了与传递的查询选择器匹配的第一个元素)。

但是,更优雅的解决方案是使用ID而不是类,因为HTML规范要求它们在开始时是唯一的(这将授予您未编写的故障安全性或生成重复的类)。因此,鉴于您的所有复选框现在都具有唯一的ID-s:

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]}`));
© www.soinside.com 2019 - 2024. All rights reserved.