2012-03-13 133 views
4

我想要设置调用函数的链接的标题文本,该函数接收元素的id作为参数并输出文本。JQuery如何使用相同元素的其他属性设置元素的属性

$(a).attr('title', function() {return $(this).id + "foo"}); 

,但像这样的构造不据我所知存在。我能做什么? 谢谢。

+0

刚才那'prop'建议在'attr'在大多数情况下为jQuery的1.7+ – mrtsherman 2012-03-13 14:48:52

回答

7

使用$(this).attr('id')this.id。做不是混合它们。

$(a).attr('title', function() {return $(this).attr('id') + "foo"}); 
$(a).attr('title', function() {return this.id + "foo"});  // <-- Preferred 
//^ Is this a a variable? If not, you have to quote it: $("a").attr(...); 
+1

+1的音符。虽然从来没有任何理由使用'$(this).attr('id')' - 输入并导致不必要的函数调用时间更长。 – 2012-03-13 14:48:19

0
$('a').each(function(){ 
    $(this).attr('title', $(this).attr('id')); 
}); 

也许?

1

使用jQuery的.each()方法:

$('a').each(function(){ 
    $(this).attr('title', this.id + ' foo'); 
}); 

参考文献:jQuery .each()

1
var id = $(this).attr('id') ; //capture the caller 
$(a).attr('title',id + 'foo'); 
相关问题