jQuery选择器对self的引用 [英] jQuery selector reference to self

查看:72
本文介绍了jQuery选择器对self的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题:

例如,当我想将html()设置为自己的属性时,如何不使用$.each()来指称自己?

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

$('*[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?

推荐答案

您可以传递函数而不是字符串.

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

您的所有示例都不起作用的原因是,在每种情况下,您的代码都在评估选择器之前执行了很长时间.这是您真正需要了解的事情-当涉及回调时,它甚至更相关.对于AJAX或计时器:当您将代码放在某处时,它会在此时执行.因此,无论foo做什么,foo(some code here)都会始终执行属于函数参数一部分的代码.避免这种情况的唯一原因是传递包含此代码的函数-对函数表达式进行求值(其结果为可调用函数).然后,实际的函数(显然需要期望一个可调用的函数而不是一个简单的值)可以在适当的时候调用传递的函数.

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.

这篇关于jQuery选择器对self的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆