开发者

Can someone help explain this jQuery code?

开发者 https://www.devze.com 2023-03-31 20:40 出处:网络
$(\'#AddMoreErrors,#AddMoreMime,#AddMoreRemote\').live(\'click\',function(){ var newRow = $(this).closest(\'tr\');
$('#AddMoreErrors,#AddMoreMime,#AddMoreRemote').live('click',function(){
    var newRow = $(this).closest('tr');
    $(this).closest('tr').after('<tr class="'+newRow.attr('class')+'">'+newRow.html()+'</tr>').find('span').removeAttr('id').addClass('removetr').html('Del');                  
});

I wrote the above jquery code and this is what it does: When som开发者_运维知识库eone clicks on "add more" it finds the nearest tr, replicates it into another tr and appends it to the first one. Then it finds all the spans, removes its id and adds a new class and changes the text.

Now what surprised me was find('span').removeAttr('id').addClass('removetr').html('Del');

I know I could do removeAttr on span but how did addClass and html also get applied on span?


jQuery returns object of element after each operation on which it is performed, and execution order are from left to right. So its .removeAttr('id') will be on span and that span object will be returned. Similarly .addClass('removetr') and .html('Del'); are performed.


Most jQuery methods return this, so:

find('span').removeAttr('id').addClass('removetr').html('Del');

Means the same as:

var foo = find('span');
foo.removeAttr('id');
foo.addClass('removetr')
foo.html('Del');


I'm not sure what you're asking, but if you want to know why you can chain jQuery commands one after another, that's because every jQuery function return "this". You can easily do the same when working with IIFEs:

function doSth() {
   // Some logic
   return this;
}

What actually happens the is, that you return the object after each method call and continue working on the same object you called the method from before.

That means that

$("#sel").method().method2().method3();

is exactly the same as writing

var sel = $("sel");
sel.method();
sel.method2();
sel.method3();

Only that it's shorter, looks nicer and you don't need to save the variable in case you don't need it again afterwards.

That way, you can write one function after another and you'll always have the complete jQuery function after the function is executed.

So you also see, why all three methods are executed on the same object: It's the way chaining works. By calling "$" you create a new object. And all methods are then executed on that object.

Unless of course, the function actually returns a value. Then, this won't work.

function getSth() {
    return "value";
}


This is called method chaining. Each of those jQuery methods (removeAttr(), addClass(), html(val)) returns the jQuery object to which it belongs. This means you can call further methods using the dot notation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号