简体   繁体   中英

Calling function with argument in a javascript object

I want to print any object. I hope you understand, what i want. I am new. Below is my code,

function abhi(x)
{
    var abhi = new Object();
    abhi.first_name = "abhijit";
    abhi.last_name = "Das";
    abhi.age = 22;
    document.getElementById("name").innerHTML = abhi.x ;
}
</script>
<p id="name"></p>
<input type="submit" name="submit" value="Name" onclick="abhi(age)"/>
</body>

In HTML you need to pass a string:

onclick="abhi('age')"

If age is a variable containing "age" , it's OK.

Then you can use it in the script like this:

document.getElementById("name").innerHTML = abhi[x];

You can read more about the bracket notation and objects at MDN .

You'll have to use square bracket notation to access properties of objects by passing a string.

document.getElementById("name").innerHTML = abhi[x];
...
<input type="submit" name="submit" value="Name" onclick="abhi('age')"/>

您必须使用此行

document.getElementById("name").innerHTML = abhi[x] ;
<script type="text/javascript">
function getAbhi(x) {

    var abhi = {
        first_name: "abhijit",
        last_name: "Das",
        age: 22
    };

    document.getElementById("name").innerHTML = abhi[x];
}
</script>

<p id="name"></p>
<input type="submit" name="submit" value="Name" onclick="getAbhi('age')" />

http://jsfiddle.net/samliew/H7Zs9/7/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM