为什么我的 .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 链接)
JSFiddle 链接: http://jsfiddle.net/ktw4v/3/
I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
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>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它将您的变量视为字符串,其第 0 个元素是
[
。发生这种情况是因为您的字符串不是 有效的 JSON,它应该使用双引号而不是单引号作为字符串分隔符引号。然后,您必须使用单引号来分隔整个属性值。
如果您修复引号,您的原始代码就可以工作(请参阅 http://jsfiddle.net/ktw4v/12/)
当 jQuery 在数据属性中看到有效的 JSON 时,它会自动为您解压。
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/)
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
将其声明为属性意味着它是一个字符串。
所以
stuff[0]
相当于:var myString = "['a','b','c']"; Alert(myString[0]);
你需要让它看起来像这样:
撤回:jQuery 的解析失败,因为它不符合 parseJSON 的规则。
但是,我会支持我的解决方案。其他解决方案在某些方面不太理想,就像这个解决方案在某些方面不太理想一样。一切都取决于您的范例是什么。
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:
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.
正如其他人所指出的,该值被视为字符串,因此它返回“[”。请尝试这个(aaa 是 div 的名称,我取出了数据内容):
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):
另一种方法发布在jsfiddle;
var stuff = $('div').data('stuff');
stuff 是一个字符串,第 0 个字符为 '['那么,
var stuff = eval($('div').data('stuff'));
应该给你一个数组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