jQuery selector reference to self

后端 未结 1 1517
误落风尘
误落风尘 2021-02-13 13:46

Simple question:

How do I refer to self without using $.each() for example when I want to set html() to own attribute?

$(\'*[re         


        
相关标签:
1条回答
  • 2021-02-13 14:45

    You can pass a function instead of a a string.

    $('[rel]').html(function() {
        return $(this).attr('rel');
    });
    

    The reason why all of your examples don't work is because in each case your code executes long before the selector has been evaluated. This is something you really need to understand - it's even more relevant when callbacks are involved e.g. for AJAX or timers: When you put code somewhere it's executed at this point. So foo(some code here) will always execute the code that's part of the function argument no matter what foo does. The only reason to avoid this is passing a function that contains this code - that was the function expression is evaluated (which evaluates to a callable function). Then the actual function (which obviously needs to expect a callable instead of a simple value) can invoke the passed function whenever it's appropriate.

    0 讨论(0)
提交回复
热议问题