简体   繁体   中英

How to make a clickable banner

I have a div and there is a link inside. 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 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.

You can fix this in a couple of ways. Firstly, check what the event target was in the div handler:

$(".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() :

$(".sc-banner").click(function(e) {
  e.stopPropagation();
  window.open('http://google.com', "_blank");
});

$(".sc-banner a").click(function(e) {
  e.stopPropagation();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM