问题描述
好吧,我想将一个非常基本的数组传递给jquery数据attrubute服务器端,如下所示:
< div数据东西= [ 'A', 'b', 'C'] >< / DIV>
然后像这样检索:
var stuff = $('div')。data('stuff');
alert(stuff [0]);
为什么会出现提示'['而不是'a'(请参阅JSfiddle链接) p>
JSFiddle链接:
它将您的变量视为一个字符串,它的第零个元素这是 [
。
这是因为你的字符串不是,它应该使用双引号作为字符串分隔符而不是单引号。您必须使用单引号来分隔整个属性值。
如果您修复了引号,您的原始代码将起作用(请参阅)
< div data-stuff ='[a,b,c]'> < / DIV>
$ b $ var stuff = $('div')。data('stuff');
当jQuery在数据属性中看到有效的JSON时,它会。
Ok so I want to pass a very basic array into a jquery data attrubute server side like so:
<div data-stuff="['a','b','c']"></div>
and then retreive like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
Why does this appear to alert '[' and not 'a' (see JSfiddle link)
JSFiddle Link : http://jsfiddle.net/ktw4v/3/
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.
这篇关于如何将数组传递给jQuery .data()属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!