-1

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/

4

1 回答 1

5

您必须获取该值,然后重新保存它:

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

这样做可能是安全的:

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

但是那种事情让我很生气。

编辑——如果你想让 jQuery 像这样理解你的 JSON,它必须是有效的:

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

仅限双引号,并且还必须引用属性名称。

于 2013-07-17T21:27:57.477 回答