【问题标题】:Accessing data from data attribute using jquery使用jquery从数据属性访问数据
【发布时间】:2013-02-12 15:19:14
【问题描述】:

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

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


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

 });

当我执行 console.log(this) 时,它会为我提供所有嵌套元素,但我不知道如何访问它们或数据区域的值。

【问题讨论】:

  • 你能具体说明你想要做什么吗?请提供您的 html 代码以及您的问题很难理解

标签: jquery css-selectors


【解决方案1】:

试试这个:try fiddle

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

【讨论】:

    【解决方案2】:

    您可以使用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();
    

    【讨论】:

      【解决方案3】:
       $('#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 总是返回元素。您需要重新访问函数内部的数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-26
        • 1970-01-01
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-20
        相关资源
        最近更新 更多