如何在 jQuery 表达式中访问当前元素的属性?

g.p*_*dou 1 javascript jquery

我想对每个选定的元素调用一个函数:

$('any valid selector').existingFunction({ p1:<myAttributeValueForTheCurrentElement> });
Run Code Online (Sandbox Code Playgroud)

我试过了:

$('any valid selector').existingFunction({ p1: this.attr('myAttributeValueForTheCurrentElement') });
Run Code Online (Sandbox Code Playgroud)

但显然这是指 HTMLDocument,因为我收到错误消息:“Object # has no method 'attr'”

Jos*_*osh 5

this绑定到外部范围。

您的代码相当于以下内容:

var obj = { p1: this.attr('myAttributeValueForTheCurrentElement') };

$('any valid selector').existingFunction(obj);
Run Code Online (Sandbox Code Playgroud)

您将需要迭代集合中的元素。

$('selector').each(function(){

   var options = { p1: $(this).attr('myAttributeValueForTheCurrentElement') };

   $(this).existingFunction(options);

});
Run Code Online (Sandbox Code Playgroud)