简体   繁体   中英

Javascript code doesn't work. Why?

The values of the buttons should change when you click on them

<html>
<head>

</head>


<body>

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

<script>

function click(objekt) {

if(objekt.value == 1)
    objekt.value = 0;
    else
        objekt.value = 1;

}

</script>


</body>
</html>

Please explain how to get the value on onclick event?

Name of your function is the culprit here. you can not name your function name "click" , it's restricted . Change your function name, it will work.

 function click123(objekt) { if (objekt.value == 1) objekt.value = 0; else objekt.value = 1; } 
 <input type="button" value="1" onclick="click123(this);"> <input type="button" value="0" onclick="click123(this);"> <input type="button" value="1" onclick="click123(this);"> 

Try removing the spaces on

<input type = "button" value ="1" onclick="click(this);">
<input type = "button" value ="0" onclick="click(this);">
<input type = "button" value ="1" onclick="click(this);">

to

<input type="button" value="1" onclick="click(this);">
<input type="button" value="0" onclick="click(this);">
<input type="button" value="1" onclick="click(this);">

Also, what are the values when you change them? Try printing them out. That might help you find what you're looking for. Does it actually change to 1 or 0? Also, I know you don't need curly brackets on if statements if there is only one statement but try with curly brackets.

Here you go with the solution https://jsfiddle.net/o0zxqq0u/

clickFunc = function(objekt) {
    if(objekt.value == 1)
        objekt.value = 0;
    else
        objekt.value = 1; 
}

**HTML**
<input type="button" value ="1" onclick="clickFunc(this);" />
<input type="button" value ="0" onclick="clickFunc(this);" />
<input type="button" value ="1" onclick="clickFunc(this);" />

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