[英]Onclick for a Image inside an anchor tag is not working
I have an image tag inside an anchor tag, the image tag has a greyed out star icon which on click I want to change it to a golden colour star icon, so inside the image tag I have written a onclick="myFunction('activity');"
我在锚标签内有一个图像标签,该图像标签上有一个灰色的星形图标,单击后我想将其更改为金色星形图标,因此在该图像标签内我编写了一个onclick="myFunction('activity');"
which does this bit. 这一点。
<a href="/projects/test-project/activity" class="activity">
<img width="16" height="16" alt="grey star" src="/img/star.png" style="position:relative;left:180px;top:3px;z-index:100" onclick="myFunction('activity');" id="activity">
Activity</a>
But the problem is that when I click on the star icon image, the onlick function works but loads up url from the href="/projects/test-project/activity"
from the anchor tag. 但是问题是,当我单击星形图标图像时,onlick函数可以工作,但会从锚标记的href="/projects/test-project/activity"
加载url。 How do I click on this image tag and make the page not get loaded? 如何单击此图像标签并使页面不被加载?
Thanks for any help 谢谢你的帮助
Remove onclick function from the html and update the code like this: 从html中删除onclick函数,并更新代码,如下所示:
HTML : HTML :
<a href="/projects/test-project/activity" class="activity">
<img width="16" height="16" alt="grey star" src="/img/star.png"
style="position:relative;left:180px;top:3px;z-index:100" id="activity">
Activity
</a>
JQuery : jQuery的 :
$(document).ready(function(){
$('#activity').click(function(event){
event.preventDefault();
myFunction('activity');
});
});
You can use jquery function as below 您可以使用jquery功能如下
$(function(){ $('#activity').on('click', function(e){ e.preventDefault(); alert('I am in'); }) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="/projects/test-project/activity" class="activity"> <img width="16" height="16" alt="grey star" src="/img/star.png" style="position:relative;left:180px;top:3px;z-index:100" id="activity"> Activity</a>
After onclick
, do event.stopPropagation()
and return false();
在onclick
之后,执行event.stopPropagation()
并return false();
event.stopPropagation()
<a href="/projects/test-project/activity" class="activity">
<img width="16" height="16" alt="grey star" src="/img/star.png" style="position:relative;left:180px;top:3px;z-index:100" onclick="myFunction('activity');event.stopPropagation();return false();" id="activity">
Activity</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.