【问题标题】:Jquery Each Json Values IssueJquery 每个 Json 值问题
【发布时间】:2012-06-23 21:39:43
【问题描述】:
<html>
<head>
    <title>testjson</title>
    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript">

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);
}
    </script>


</head>
<body>
<input type="button" value="save" onclick="saveChanges();"/>
<input type="text" name="Surname" id="text1" class="InputText" /><br>
<input type="text" name="Surname" id="text2" class="InputText"/><br>
<input type="text" name="Surname" id="text3" class="InputText"/><br>

</body>
</html>

得到了上面的代码块,我希望能够动态获取输入 ID,并使用 ID 在 incdientReport1 json 中分配一个值。当我做这个问题时似乎是这条线......

var temp = (input.attr('id')); 

在分配 ID 并在控制台中显示时,它可以正常工作

但是当这行代码

 incidentReport1.temp = input.val();

运行它会将其保存到一个名为 temp 的新字段,而不是 temp.. 的字符串值。

这么困惑的家伙我哪里错了?

【问题讨论】:

    标签: javascript jquery json javascript-objects


    【解决方案1】:

    你想要:

    incidentReport1[temp] = input.val();
    

    当您需要使用计算属性名称时,您可以使用[ ] 运算符。也就是说,

    object.propertyName
    

    相同
    object[ "propertyName" ]
    

    【讨论】:

    • 这个,当你使用 object.value Javascript 解释 object["value"]
    • 谢谢,真不敢相信事情这么简单!很好的答案!
    猜你喜欢
    • 1970-01-01
    • 2011-01-06
    • 2011-11-19
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多