0

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

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

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

谢谢!

4

3 回答 3

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()循环中为匹配集中的每个元素调用一次。查看您正在使用的插件的源代码表明情况并非如此。

于 2012-09-25T13:43:58.230 回答
2

我认为你应该这样使用

$(".chained").each(function(){
//add data as you want
})
于 2012-09-25T13:44:20.537 回答
0

尝试使用

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

或者

$(this).data('chainedParent')
于 2012-09-25T13:44:16.393 回答