如何使用jquery获取数据属性的值

How to get value of data attribute with jquery

本文关键字:数据属性 获取 何使用 jquery      更新时间:2023-09-26

我希望能够获取html5属性值,并使它们与类的值和属性名称相匹配,然后在单击时隐藏。

例如,对于sample14和该页面上的任何其他属性,data-table="sample11"应该隐藏相同的class="sample11"

我试过这样的东西,但对我不起作用——下面是我尝试的方法——这是我的小提琴http://jsfiddle.net/breezy/xq6epy39/

任何帮助或指导都会有所帮助。谢谢

<div data-table="sample11">
  <a href="#">when i click this 'hide this' in sample11 should hide</a>
</div>
<div class="sample11">
  hide this
</div>

<div data-table="sample14">
   <a href="#">when i click this 'hide this' in sample14 should hide</a>
</div>
<div class="sample14">
  hide this
</div>

jQuery

var sample = $('div').data("table") === "11";
sample.click(function() {
  $('.sample11').hide();
});

try:

$('div a').click(function(e) {
  e.preventDefault();
  $('.' + $(this).parent().attr('data-table')).toggle();//hide()//slideToggle()//fadeToggle()
});

http://jsfiddle.net/4Lor0md5/

您可以使用[]指定属性。使用jquery选择器有几个选项。

var sample = $('div[data-table="11"]');
sample.click(function() {
  $('.sample11').hide();
});

您可以将数据属性与jquery一起使用。我已经修改了你的代码

<div>
   <a href="#" class="clickme" data-table=".sample14">when i click this 'hide this' in sample14 should hide</a>
</div>
<div class="sample14">
  hide this
</div>
$(".clickme").click(function(){
  alert($(this).data("table"));
  $($(this).data("table")).hide();
})

代替隐藏,您可以调用隐藏/取消隐藏的切换函数。