使用jquery从data属性访问数据

时间:2013-02-12 06:51:39

标签: jquery css-selectors

我一直试图在数据属性被设置后访问数据和嵌套元素,但我没有运气,这里是代码:

 $('#item-prize-location').find('[data-region]').each(function(){


  //want to access data-region value
      //want to access nested divs with        

 });

当我做一个console.log(这个)给我所有嵌套元素,但我不知道如何访问它们或数据区域的值。

3 个答案:

答案 0 :(得分:0)

您可以使用dataset属性或jQuery data方法:

$('#item-prize-location').find('[data-region]').each(function(){
      var region = this.dataset.region;
      // var region = $(this).data('region');
});

您还可以使用map方法并将值存储在数组中。

var regions = $('#item-prize-location div[data-region]').map(function(){
      return this.dataset.region;
}).get();

答案 1 :(得分:0)

 $('#item-prize-location').find('[data-region]').each(function(){

mydata=$(this).attr('data-region') //or mydata=$(this).data('region') 
//do stuff with mydata-- that is the data in the selected element
//for example:
console.log(mydata)
//You can access the element itself using `this` or $(this)


 });

$.each始终返回元素。您需要重新访问函数内的数据。

答案 2 :(得分:0)

试试这个:try fiddle

$('#item-prize-location').find('[data-region]').each(function(){
   console.log($(this).data('region'));       
});
相关问题