Why is object/associative array values not setting when I use $item.data("something").x
Why is it when I do something like
http://jsfiddle.net/sUhn9/
Added relevant HTML
<div id="container" data-physics='{x: 10, y: 5}'>Hello</div>
开发者_运维知识库
JavaScript:
$(function() {
var obj = $("#container").data("physics");
console.log("b4", obj);
obj.x = -2;
obj.y = -6;
console.log("after", obj);
});
I get
b4 {x: 10, y: 5}
after {x: 10, y: 5}
Where x and y are not being set
Your obj is not an object, it's a string. Changing the x and y properties for the string will not change the string itself.
You should do something like this:
var obj = jQuery.parseJSON($("#container").data("physics"));
Working update here !!!
Well, for data-physics='{x: 10, y: 5}'
var obj = $("#container").data("physics");
returns string so obj
is not an object so no property and ...
So to get it right, make it data-physics='{"x": 10, "y": 5}'
, and everything should work fine.
精彩评论