【问题标题】:Understanding jQuery Selector using foreach使用 foreach 理解 jQuery 选择器
【发布时间】:2023-03-05 21:20:01
【问题描述】:

我无法理解为什么我的选择器不适用于 foreach 循环。

我的 DOM 看起来是这样的:

<div id="page1" class="ui-droppable">

    <div class="ui-draggable ui-draggable-handle ui-draggable-dragging signatureInstance selected btn-delete" style="position: absolute; left: 185px; top: 470px;">
        <img src="http://example.com/img/field.png">
        <span class="glyphicon glyphicon-remove btn-delete"><span></span></span>
    </div>

    <div class="ui-draggable ui-draggable-handle ui-draggable-dragging signatureInstance selected btn-delete" style="position: absolute; left: 171px; top: 562px;">
        <img src="http://example.com/img/field.png">
        <span class="glyphicon glyphicon-remove btn-delete"><span></span></span>
    </div>

</div>

有人能解释一下为什么以下选择器对 foreach 迭代无效吗?

$('#page1 .signatureInstance').forEach(function(index) {
    console.log($(this));
});

$('#page1 .ui-draggable .ui-draggable-handle .ui-draggable-dragging signatureInstance .selected .btn-delete').forEach(function(index) {
    console.log($(this));
});

甚至:

$('#page1 div').forEach(function(index) {
    console.log($(this));
});

【问题讨论】:

    标签: jquery foreach jquery-selectors


    【解决方案1】:

    您需要使用 each() 来迭代 jQuery 对象,它是为它构建的。

    .each() 方法旨在使 DOM 循环结构简洁且不易出错。当被调用时,它会遍历作为 jQuery 对象一部分的 DOM 元素。每次回调运行时,都会传递当前循环迭代,从 0 开始。更重要的是,回调是在当前 DOM 元素的上下文中触发的,因此关键字 this 指的是该元素。 (取自https://api.jquery.com/each/

    Array.prototype.forEach() 用于迭代数组而不是用于 jQuery 对象集合。

    $('#page1 .signatureInstance').each(function(index) {
        console.log($(this));
    });
    

    为了更好地理解Iterating over jQuery and non-jQuery Objects

    【讨论】:

    • 好吧,我觉得自己很傻。谢谢你。非常感谢您的帮助!
    • @Nathan_Sharktek :很高兴为您提供帮助
    猜你喜欢
    • 2021-08-17
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多