attr() 值回调有什么用途

值回调就是给参数传入一个函数。每个匹配的元素都调用一次该函数。。。我不是很明白。。比如什么情况下用这个号。。最好给个实际运用的案例

阅读 3.6k
2 个回答

这里不是说的挺明白的么 http://api.jquery.com/attr/#a...

function
Type: Function( Integer index, String attr ) => String or Number
A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.

比如你有个<div id="hello" world="2"></div>
你想每次都给world自增1
可以这么做

jQuery('#hello').attr('world',function(i,old){
    return ~~old+1;
});

ps:你不问我还不知道有这个回调呢,哈哈

获取属性

var id = $(el).attr('id');

设置属性

$(el).attr('class','class1');
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进