javascript 图像点击不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19464637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:40:55  来源:igfitidea点击:

Image onclick not working

javascript

提问by Abhi

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();
}

回答by jeff

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

您是否 100% 确定对 abc() 的调用不起作用?控制台日志中是否有任何错误。

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.

你也可以考虑事件冒泡。你点击图像,它会触发它的事件。然后冒泡到 a href 元素,然后冒泡到下一个可用元素等等。

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.

这将防止事件冒泡比 img onclick 函数更进一步。

回答by Praveenram Balachandar

Since your imgis inside an atag, the click on the image would cause a click on the aand hence you see the hyperlink working.

由于您img位于a标签内,因此单击图像会导致单击a,因此您会看到超链接正在工作。

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

如果您改为将 onclick 放在a它上面会触发函数调用。

回答by Sid M

Just add your function abc()inside script tags

只需添加您的function abc()内部脚本标签

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

回答by Manish Sharma

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

试试这个,并src="imagepath"添加你的图像路径

<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>