jquery - 为什么我们需要在 .each() 函数中使用 $(this) ?

标签 jquery

我是编程新手,发现这段代码有点令人困惑。我知道选择所有类型为文本的输入字段的行会循环遍历每个字段。

那么为什么它使用 $(this) 因为它已经做出了选择,这是所有类型为文本的输入字段。

$('#combine').click(function() {
    var combined_text = "";
    $('input[type="text"]').each(function() {
        combined_text += $(this).val() + ' ';
    });
    alert(combined_text);
});

最佳答案

From docs directly

The .each() method is designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element.

To access a jQuery object instead of the regular DOM element, use $(this).

Some good explanation here

关于jquery - 为什么我们需要在 .each() 函数中使用 $(this) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17671927/

相关文章:

javascript - 在一个页面上同时显示级联列表

jquery窗口调整大小请帮忙

javascript - 在ajax内部调用ajax

jquery - 如何让一个元素响应另一个元素的点击? - CSS/jQuery

jQuery - 输入列表中每个元素的 .prepend() ?

javascript - 从动态元素列表中获取选择器事件索引

javascript - 如何显示 Bootstrap 箱关闭前的剩余秒数?

jQuery on() 和 stopPropagation()

jquery - jsFiddle 说 jQuery 代码不正确,但在我的网站上仍然有效

javascript - Jquery 切换和添加/删除