【问题标题】:Value not being fetched from data-x tags未从 data-x 标签中获取值
【发布时间】:2012-11-02 03:12:03
【问题描述】:

我正在尝试从元素中包含的两个数据属性中获取值。 如果我使用:

data = $('tr th', a).data() ;

然后尝试使用:

data[0] // This works.
data[1] // Comes out as undefined.

这是我的脚本中执行此操作的部分,它目前有效,因为我正在使用 .attr() 来获取值:

$('tr th', a).each(function(){
        sql = $(this).attr('data-sql') ;
        dir = $(this).attr('data-direction') ;

        if(sql)
        {
            JSONCols += '"'+sql+'", ' ;
        }
        if(!dir)
        {
            dir = '' ;
        }
        JSONDirs += '"'+dir+'", ' ;
    })

我怎样才能只使用 .data() 来获取两个值而不是使用 .attr() 以便我的代码更干净?

【问题讨论】:

    标签: jquery json html loops attributes


    【解决方案1】:

    把它当作一个对象,data.sqldata.direction

    但请注意,这只会从第一个选定元素中获取数据。如果您想从它们中获取所有数据,则必须使用迭代函数,例如 for loopwhile loop$.each$().each$.map$().map

    var data = $('tr th', a).map(function(){
        return $(this).data();
    }).get();
    console.log(data[0].sql);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      相关资源
      最近更新 更多