为什么我的. data()函数返回[而不是数组的第一个值?

我想将一个数组传递到服务器端的 jQuery 数据属性中,然后像下面这样检索它:

var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>

为什么这看起来像是警告“[”而不是“ a”(参见 JSFiddle 链接)

返回文章页面 http://JSFiddle.net/ktw4v/3/

96101 次浏览

It's treating your variable as a string, the zeroth element of which is [.

This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.

If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)

<div data-stuff='["a","b","c"]'> </div>


var stuff = $('div').data('stuff');

When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.

Declaring it as an attribute means that it is a string.

So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);

You need to make it look like this:

<div data-stuff="a,b,c"></div>


var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);

Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.

However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.

A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['

Well, var stuff = eval($('div').data('stuff')); should get you an array

As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):

$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});