简体   繁体   中英

using javascript in the onclick attribute

i posted a question earlier and got it answerd thanks to the wonderful people here, but as my luck goes, its never that easy. i have a code that switches back and forth between pictures onclick, however, the first time you click, the picture doesnt switch, but the checkbox is checked. at the very least a reasoning would be superb :)

<script type="text/javascript">
function func()
{
    var img1= document.getElementById("img1");

    if(img1.name == "on")
    {
        img1.src = "images/" + "img1a.jpg";
        img1.name = "off";
    }
    else
    {
        img1.src = "images/" + "img1.jpg";
        img1.name = "on";
    }
}
</script>



</head>

<body>
<form>
<p align="center">
<input type="checkbox" name="interest1" id="interest1" value="x">
<input type="checkbox" name="interest2" id="interest2" value="x">
<input type="checkbox" name="interest3" id="interest3" value="x"></p>   
<p align="center">
<label for="interest1" id="label-interest1"><img src="images/img1.jpg" width="781" height="800" onclick="func()" id="img1" /></label>
<label for="interest2" id="label-interest2"><img src="/images/img2.jpg" width="781" height="800" /></label>
<label for="interest3" id="label-interest3"><img src="/images/img3.jpg" width="781" height="800" /></label></P><!-- code making checkbox be an image-->
</form>

You are lacking the first state of "on". Try adding this to your markup

 <img src="images/img1.jpg" width="781" height="800" onclick="func()" name="on" id="img1" />

Conversely, you could handle this in javascript in your conditional statement like this:

if(img1.name === undefined || img1.name == "on")

which would handle the first state where a name attribute was not present.

Since your img element doesn't have a name attribute, it doesn't match "on" condition the first time it is clicked. You could add a name attribute (which would work, but make the html invalid), but a better solution might be to get the value from the checkbox you are associating it with. Something like this:

var checkboxid = img1.parentNode.getAttribute("for");
document.getElementById(checkboxid).checked

This way, you can be sure it is kept in sync with the checkbox.

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