简体   繁体   English

Ajax调用后无法访问新元素(Vanilla JS)

[英]Can't access new elements after Ajax call (Vanilla JS)

I have an ajax call that is populating a list with items, but after the call is completed I can't access the list items in the DOM to add eventlisteners, console.log outputs an empty nodeList. 我有一个用项填充列表的ajax调用,但是调用完成后,我无法访问DOM中的列表项以添加事件监听器,console.log输出一个空的nodeList。

My HTML : 我的HTML

<ul class="list"></ul>

My JS file: 我的JS文件:

let list = document.querySelector('.list'),
listitem = document.querySelectorAll('.list-item'),
content;

function showItems() {

    let url = 'https://swapi.co/api/people';
    fetch(url)
    .then(function(response) {
        return response.json();
    }).then(function(data) {
        let results = data.results;
        results.forEach(item => {
            content = `<li class="list-item"><a href="#">${item.name}</a></li>`;
            list.innerHTML += content;
        });

        //This displays the entire content
        console.log(list);

        //This doens't find the child elements
        console.log(listitem);

    }).catch(function(err) {
        console.log(err);
    });
}

showItems();

The weird thing is if I console.log the list it displays the newly created elements, but if I try to console.log the list-item directly, the result is NodeList(0) and I believe that if the call wasn't finished the complete list shouldn't show the list items as well. 奇怪的是,如果我在console.log list显示了新创建的元素,但是如果我尝试在console.log中直接显示list-item ,则结果为NodeList(0)并且我认为如果调用未完成完整列表也不应显示列表项。

There is a test here: https://jsfiddle.net/magutj8L/1/ 这里有一个测试: https : //jsfiddle.net/magutj8L/1/

NOTE: I don't want to use JQuery. 注意:我不想使用JQuery。

querySelectorAll returns a static NodeList . querySelectorAll返回一个静态 NodeList If you call document.querySelectorAll , it will return whatever matching elements exist at the time you called it - it won't automatically update to include new elements. 如果你打电话document.querySelectorAll ,它将返回任何匹配的元素在你叫它时存在-它不会自动更新,包括新的元素。 (This is arguably more intuitive than were the situation reversed - you don't really want a variable to mutate itself while you're iterating over it, this is a frequent source of bugs) (这可以说比情况逆转时更直观-在迭代过程中,您真的不希望变量发生突变,这是错误的常见来源)

You should select the elements again after the list is populated: 填充列表后,您应该再次选择元素:

const newListitems = document.querySelectorAll('.list-item');
console.log(newListitems);

Note that getElementsByClassName is an option, which will return a live HTMLCollection - the new elements added will be present in the collection, without selecting them again: 请注意, getElementsByClassName是一个选项,它将返回一个实时 HTMLCollection添加的新元素将出现在该集合中,而无需再次选择它们:

listitem = document.getElementsByClassName('list-item')

But, IMO, live collections are unintuitive, so I wouldn't recommend using logic that depends on it. 但是,对于IMO,实时收集是不直观的,因此我不建议您使用依赖于此的逻辑。

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

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