当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - how to set property within property in jQuery data()

问题描述:

If I know that a certain data property exists on an element and it is an object, how can I store something as a new property of that data object?

For example, I have this div:

<div id="theDiv" data-test1="{string: 'test 1 data'}"></div>

And I'm trying to set data on it like this:

div.data(["test1"]["number"], 1);

But that is getting me nowhere. And div.data(["test1"]["number"]) = 1; gets me a left-hand side in assignment error.

http://jsfiddle.net/VM8VW/

网友答案:

You have to fetch the value and then re-save it:

div.data('test1', function(prev) {
  prev.number = 1;
  return prev;
}(div.data('test1')));

It's probably safe to just do this:

div.data('test1').number = 1;

but that sort of thing gives me the willies.

edit — if you want jQuery to understand your JSON as such, it has to be valid:

<div id="theDiv" data-test1='{"string": "test 1 data"}'></div>

Double quotes only, and property names must also be quoted.

分享给朋友:
您可能感兴趣的文章:
随机阅读: