Jquery每个Json值问题
testjson var incidentReport1 = { "text1": "n/a", "text2": "n/a", "text3": "n/a", } function readHtmlForInputs() { var count = 0; //Setting count to 0 $('input').each(function(){ var input = $(this); var temp = (input.attr('id')); if(input.attr('type') == 'button'){alert('button');} else{ incidentReport1.temp = input.val(); count++; //Incrementing counter } }); console.log("Input Types Found:" + count); } function saveChanges() { readHtmlForInputs(); console.dir(incidentReport1); }
得到上面的代码块,我希望能够动态获取输入ID,并使用ID在incdientReport1 json中分配值。 当我这样做时,问题似乎就是这一行……
var temp = (input.attr('id'));
分配ID并在控制台中显示它时,它可以正常工作
但是当这行代码
incidentReport1.temp = input.val();
运行它将它保存到一个名为temp的新域,而不是temp的字符串值。
这么困惑的家伙我哪里错了?
你要:
incidentReport1[temp] = input.val();
当您需要使用计算属性名称时,使用[ ]
运算符。 那是,
object.propertyName
是相同的
object[ "propertyName" ]