Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 未从data-x标记中提取值_Jquery_Json_Html_Loops_Attributes - Fatal编程技术网

Jquery 未从data-x标记中提取值

Jquery 未从data-x标记中提取值,jquery,json,html,loops,attributes,Jquery,Json,Html,Loops,Attributes,我试图从元素中包含的两个数据属性中获取值。 如果我使用: 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') ;

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

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+'", ' ;
    })

如何使用just.data()来获取这两个值,而不是使用.attr(),这样我的代码更干净?

将其视为对象,
data.sql
data.direction

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

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