简体   繁体   English

如何在 Javascript 中使用 For 循环,就像 jQuery 中的 Each 循环

[英]How to use For loop in Javascript, like Each loop in jQuery

It's very easy to use Each loop in jQuery.在 jQuery 中使用 Each 循环非常容易。 But I want to use For loop in JS, without using jQuery.但我想在 JS 中使用 For 循环,而不使用 jQuery。

I can use Each loop like this.我可以像这样使用 Each 循环。 And $(this) selector is very helpful to reach child elements.$(this)选择器对于访问子元素非常有帮助。

$('.documents .document.selected').each(function(index){
    console.log($(this).find('.document-name p').text())//this code gives me all selected element's name
})

I want to reach child elements by using For loop, but this code doesn't even works...我想通过使用 For 循环来访问子元素,但此代码甚至不起作用...

for (let i = 0; i < $('.documents .document.selected').length; i++) {
    console.log($('.documents .document.selected')[i].find('.document-name p').text())//but this is not
}

I want to use For loop by using $(this) selector, but it's not working with For loop:我想通过使用$(this)选择器来使用 For 循环,但它不适用于 For 循环:

for (let i = 0; i < $('.documents .document.selected').length; i++) {
    console.log($(this).find('.document-name p').text())
}

How to use For loop very easy as I show you or do you have any suggest?正如我向您展示的那样,如何非常容易地使用 For 循环,或者您有什么建议吗?

Your code doesn't work because accessing an array-index property on an jQuery collection gives you the native DOM element in return, not a jQuery collection containing the element.您的代码不起作用,因为访问 jQuery 集合上的 array-index 属性会返回本机 DOM 元素,而不是包含该元素的 jQuery 集合。

$('.documents .document.selected')[i].find

should be应该

$('.documents .document.selected').eq(i).find

But that's still using jQuery.但这仍然使用jQuery。 If you want to avoid jQuery completely, you need to remove all references to $ .如果您想完全避免使用 jQuery,则需要删除对$所有引用。 Try:尝试:

const selectedDocs = document.querySelectorAll('.documents .document.selected');
for (let i = 0; i < selectedDocs.length; i++) {
    console.log(selectedDocs[i].querySelector('.document-name p').textContent);
}

Or avoid manual iteration and invoke the iterator instead:或者避免手动迭代并改为调用迭代器:

for (const selectedDoc of document.querySelectorAll('.documents .document.selected')) {
    console.log(selectedDoc.querySelector('.document-name p').textContent);
}

querySelector is the vanilla DOM method equivalent of jQuery's .find . querySelector是相当于 jQuery 的.find的 vanilla DOM 方法。

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

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