简体   繁体   中英

Why do we need to use $(this) in a .each() function?

I am new to programming and am finding this code a bit confusing. I know that the line that is selecting all input fields with the type text, loops through each field.

So why it using $(this) because it already made a selection, which was all input fields with the type text.

$('#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.

And

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

Some good explanation here

Inside the each() callback function, this refers to the dom element, not to a jQuery wrapped element.

So when you need to access jQuery methods, you need to wrap it using $(this) .

Ex

if you say this.value , it will give the value of the element inside the loop

Using the .each function starts a loop through the matched elements.

$(this) , refers to the current element, belonging to the group of matched elements!

each is jQuery loop function , So, inside each every matching element will consider individual object for jQuery. If you use JavaScript then you can use this.value but here you are playing with jQuery so you have to follow jQuery rules. Because, val is jQuery function to get current object value hence you have to use $(this) . Because $ will change this to a jQuery Object . :)

in JavaScript we can get object value by 'this.value();' in loop

in jQuery we can use above code but right baby is '$(this).val();'

使用$(this)获取$('input [type =“ text”]')==>段落中的所有输入文本

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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