简单问题:
例如,当我想将 html()
设置为自己的属性时,如何在不使用 $.each()
的情况下引用 self?
$('*[rel]').html($(this).attr('rel')); // nope
$('*[rel]').html($(self).attr('rel')); // nah
$('*[rel]').html($(sender).attr('rel')); // undefined
$('*[rel]').html($(target).attr('rel')); // still undefined
$('*[rel]').html($(???).attr('rel')); // this isn't even correct syntax
$('*[rel]').html($(beer).attr('rel')); // well that would be tasty
$('*[rel]').html($(woman).attr('rel')); // not in this life
$('*[rel]').html($(god help me!).attr('rel')); // He probably doesn't even know how to use a computer
$('*[rel]').html($(i give up).attr('rel')); // unexpected... o'rly?
最佳答案
You can pass a function instead of a a string.
$('[rel]').html(function() {
return $(this).attr('rel');
});
所有示例都不起作用的原因是,在每种情况下,您的代码都会在选择器评估之前很久就执行。这是你真正需要理解的事情 - 当涉及回调时,它甚至更相关,例如对于 AJAX 或计时器:当您将代码放在某处时,它会在此时执行。因此,无论 foo
做什么,foo(some code here)
都会始终执行函数参数中的代码。避免这种情况的唯一原因是传递包含此代码的函数 - 即计算函数表达式(计算结果为可调用函数)。然后实际的函数(显然需要一个可调用的而不是一个简单的值)可以在适当的时候调用传递的函数。
关于jQuery 选择器引用 self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18834431/