繁体   English   中英

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

[英]jQuery class selector - accessing attributes on selected element?

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

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

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

谢谢!

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

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

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

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

我想你应该这样使用

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

尝试使用

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

要么

$(this).data('chainedParent')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM