I want to know, how to dynamically change the value of a json property on a jquery event and then loads it up on the browser. Here's the sample json.
var spiderman = {
"fname" : "Peter",
"lname" : "Parker",
"nick" : "Spidey"
}
and here's the event, let's say... a click event
HTML code
Input a new nickname:<br />
<input type="text" id="newNick" />
<div id="pressMe">Press Me!</div>
<div id="output"></div>
jQuery event
$("#pressMe").click(function(){
var newNick = $("#newNick").val();
/* please place the correct code here */
$("#output").text("Spiderman's new nick is " + spiderman.nick);
})
The goal is: The user inputs the new nickname. When the user clicks #pres开发者_C百科sMe, it will get the value of #newNick and place it inside json to change the "nick" property. After that... it will show the new "nick" property on #output.
I hope its not confusing. Thank you!
This should work fine:
spiderman.nick = newNick;
Remember that if the JSON comes from an AJAX request and you loaded it with jQuery (or eval
), then object properties are accessible as I wrote (even if you see them quoted if you look at the raw response). If you defined the JSON in memory, then you don't need to use quotes on property names, but instead you should write:
var spiderman = {
fname : "Peter",
lname : "Parker",
nick : "Spidey"
}
You can just assign to the json object's property
spiderman.nick = newNick;
http://jsfiddle.net/s57YR/
I'm sure you just overlooked this, but this should work:
$("#pressMe").click(function(){
var newNick = $("#newNick").val();
spiderman.nick = newNick;
$("#output").text("Spiderman's new nick is " + spiderman.nick);
});
精彩评论