gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:49:13 25 4
gpt4 key购买 nike

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

那么为什么它使用 $(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com