我是编程新手,发现这段代码有点令人困惑。我知道选择所有类型为文本的输入字段的行会循环遍历每个字段。
那么为什么它使用 $(this)
因为它已经做出了选择,这是所有类型为文本的输入字段。
$('#combine').click(function() {
var combined_text = "";
$('input[type="text"]').each(function() {
combined_text += $(this).val() + ' ';
});
alert(combined_text);
});
最佳答案
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).
关于jquery - 为什么我们需要在 .each() 函数中使用 $(this) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17671927/