jQuery类选择器 - 访问所选元素的属性?

时间:2012-09-25 13:41:55

标签: javascript jquery

我目前有一个页面,其中包含多个“chained”类的元素。我想使用类选择器,以便我可以选择所有这些,并根据一些数据属性(每个元素将有所不同)运行一些额外的代码。到目前为止我的代码是:

$('.chained_child').remoteChainedTo('chained_parent'
   + $(this).data('chained-parent'), $(this).data('chained-url'));

我认为问题在于这部分:$(this).data('chained-parent') - 这似乎不起作用。如何选择所选元素的数据属性?

谢谢!

3 个答案:

答案 0 :(得分:4)

您可以使用.each()方法迭代匹配的元素集并为每个元素运行一个函数:

$('.chained_child').each(function () {
    $(this).remoteChainedTo('chained_parent' + $(this).data('chained-parent'), $(this).data('chained-url'));
});

正如您在上面的代码中看到的,.each()回调this内部引用了当前的底层DOM节点(不是jQuery对象,因此需要将其传递给jQuery)。

请注意,一些jQuery方法将接受一个函数作为单个参数,对于隐式.each()循环中匹配集中的每个元素,将调用一次该参数。查看您正在使用的插件的来源,这表明情况并非如此。

答案 1 :(得分:2)

我认为你应该像这样使用

$(".chained").each(function(){
//add data as you want
})

答案 2 :(得分:0)

尝试使用

$(this).attr('data-chained-parent')

OR

$(this).data('chainedParent')
相关问题