Jquery Each Json Values Issue

2019-08-29 12:42发布

问题:

<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>

Got the above block of code, an i want to be able to dynamic take the inputs ID, and use the ID to assign a value in incdientReport1 json. When i do this issue seems to be this line...

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

When assigning the ID and displaying it in console it works fine

But when this line of code

 incidentReport1.temp = input.val();

Runs it saves it to a new feild called temp rather than the string value of temp..

So confused guys where am i going wrong?

回答1:

You want:

incidentReport1[temp] = input.val();

When you need to use a computed property name, you use the [ ] operator. That is,

object.propertyName

is the same as

object[ "propertyName" ]