admin管理员组

文章数量:1287858

I have an image which is set relative to a background image. I want to call a function on the click but i seem to have been facing a problem. The hyperlink seems to be working but the function is not being called. This is how my code looks like

<img src=".."  width="100%" height="80"   id="ril_logo"/>
     <div id="logo-wrapper1">
    <img src="..."  width="5%" height="45"/>
     </div>
     <div id="logo-wrapper2">
    <a href="#">
            <img id="charger" onclick="abc();"  src=".."  width="4%" height="50" /> 
    </a>
     </div>



function abc()
{
        alert();
}

I have an image which is set relative to a background image. I want to call a function on the click but i seem to have been facing a problem. The hyperlink seems to be working but the function is not being called. This is how my code looks like

<img src=".."  width="100%" height="80"   id="ril_logo"/>
     <div id="logo-wrapper1">
    <img src="..."  width="5%" height="45"/>
     </div>
     <div id="logo-wrapper2">
    <a href="#">
            <img id="charger" onclick="abc();"  src=".."  width="4%" height="50" /> 
    </a>
     </div>



function abc()
{
        alert();
}
Share Improve this question asked Oct 19, 2013 at 9:46 AbhiAbhi 751 gold badge3 silver badges10 bronze badges 1
  • 1 Any reason why you're not using unobstrusive JS? – Richard Peck Commented Oct 19, 2013 at 9:48
Add a ment  | 

4 Answers 4

Reset to default 4

Are you 100% sure that the call to abc() is not working? Is there any errors in the console log.

Also you might consider event bubbling. You click on the image and it fires of it's event. This then bubbles to the a href element which then bubbles to the next available element and so forth etc.

Your code could be changed to:

<img id="charger" onclick="abc(); return false;" src=".." width="4%" height="50" />

or

<img id="charger" onclick="return abc();" src=".." width="4%" height="50" />
function abc() { ... return false; }

This will prevent the event bubbling any further than the img onclick function.

Since your img is inside an a tag, the click on the image would cause a click on the a and hence you see the hyperlink working.

If you instead put the onclick on a it would trigger the function call.

try this, and src="imagepath" add your image path

<img src=".." width="100%" height="80" id="ril_logo" />
<div id="logo-wrapper1">
    <img src="..." width="5%" height="45" />
</div>
<div id="logo-wrapper2">
    <a href="#">
        <img id="charger" onclick="abc();" src=".." width="4%" height="50" />
    </a>
</div>
<script type="text/javascript">

    function abc() {
        alert();
    }
</script>

Just add your function abc() inside script tags

<script type="text/javascript">
    function abc() {
        alert("Success");
    }
</script>

本文标签: javascriptImage onclick not workingStack Overflow