开发者

JavaScript changing image source not persisting

开发者 https://www.devze.com 2023-03-31 02:59 出处:网络
开发者_如何学GoI have to change an image source when the image is clicked. The issue is the image changes only during the execution of the function, but revert to its initial value immediately after!
开发者_如何学Go

I have to change an image source when the image is clicked. The issue is the image changes only during the execution of the function, but revert to its initial value immediately after!!!

This is what I have done so far:

<head>
<title></title>
<script type="text/javascript">
    function cardMouseClick(obj) {
        el = document.getElementById(obj);
        el.src = "image2.jpg";
    alert("Hello!");        
    }
</script>
</head>
<body>
<form id="form1">
   <input type="image" id="b1" src="image1.jpg"  
      onclick="cardMouseClick('b1')"/>

</form>
</body>

The image2 is duly displayed while the alert popup Windows awaits for user to click OK. Then it reverts to image1!

Why?


You have to prevent a page reload:

<form id="form1">
   <input type="image" id="b1" src="image1.jpg"  
      onclick="cardMouseClick('b1'); return false;"/>
</form>


Because its submitting the form. return false from cardMouseClick(...).


You can do like this.

        <head>
        <title></title>
        <script type="text/javascript">
              function cardMouseClick(obj) {
                    el = document.getElementById(obj);
                    el.src = "image2.jpg";
                    alert("Hello!");
                    return false;          
                   }
        </script>
       </head>
       <body>
       <form id="form1">
          <input type="image" id="b1" src="image1.jpg"  
            onclick="cardMouseClick('b1')"/>
       </form>
0

精彩评论

暂无评论...
验证码 换一张
取 消