当点击图像时,我想停止冒泡。我不能根据需要在href上设置javascript void。我使用过stopPropagation,但它不起作用。
function showurl(e){
e.stopPropagation()
window.location="http://www.yahoo.co.in"
}
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" onclick="showurl(event)" />
</a>发布于 2014-09-11 14:32:09
由于这是一个jQuery问题,我建议永远不要使用onclick属性。它们只支持单个处理程序,而且它们“丑陋”(读起来:更难找到和维护) :)
$('img").onclick = function(e) {
e.preventDefault();
window.location="http://www.yahoo.co.in";
}或
$('img").onclick = function() {
window.location="http://www.yahoo.co.in";
// return false here does the same as e.stopPropagation() and e.preventDefault();
return false;
}由于此处理程序适用于所有img元素,因此您可能需要数据驱动整个事件(使用属性),如下所示:
将目标url作为data-url属性放在图像中
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png"
data-url="http://www.yahoo.co.in" />
</a>从代码上讲:
$('img").onclick = function(e) {
// See if image has a data-url attribute
var url = $(this).data('url');
if (url){
window.location=url;
// only prevent default if it was an image with a link attribute
e.preventDefault();
}
}发布于 2014-09-11 14:40:02
我建议从JS绑定它,即使使用基本的onclick,然后使用return false;或preventDefault。(演示)
document.getElementsByTagName("img")[0].onclick = function() {
window.location="http://www.yahoo.co.in";
return false;
}HTML
<a href="http://www.google.com">
<img src="http://media.expedia.com/media/content/shared/images/navigation/expedia.co.in.png" />
</a>https://stackoverflow.com/questions/25790161
复制相似问题