[英]How to make a clickable banner
I have a div
and there is a link inside. 我有一个
div
,里面有一个链接。 When I click on a div, it should open the link (ex: google.com) but when I click the button it should open another link. 当我单击一个div时,它应该打开链接(例如:google.com),但是当我单击该按钮时,它应该打开另一个链接。
<div class="sc-banner">
<a href="#" target="_blank">Button</a>
</div>
$(".sc-banner").click(function (event) {
event.stopPropagation();
window.open ('http://google.com', "_blank");
});
The issue is because the click event from the a
is propagating up the DOM and firing the click handler on the div. 问题是因为来自
a
的click事件正在传播DOM并触发div上的click处理程序。
You can fix this in a couple of ways. 您可以通过两种方法解决此问题。 Firstly, check what the event target was in the
div
handler: 首先,检查
div
处理程序中的事件目标:
$(".sc-banner").click(function(e) {
e.stopPropagation();
if (e.target.tagName !== 'A')
window.open('http://google.com', "_blank");
});
Alternatively you could add another event handler to the a
which calls stopPropagation()
: 或者,您可以向调用
stopPropagation()
的a
添加另一个事件处理程序:
$(".sc-banner").click(function(e) {
e.stopPropagation();
window.open('http://google.com', "_blank");
});
$(".sc-banner a").click(function(e) {
e.stopPropagation();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.