简体   繁体   中英

Detect specific link clicked with href and onclick=“setLocation()”

I am trying to detect if a link was clicked with JS . This is my code:

<div onclick="setLocation('http://domain.com/test')" class="gd-details" id="detail-box2">
    <h2 class="gd-product-name">
        <a title="test" href="http://domain.com/test">content 1</a>
    </h2>    
</div>

I'm also trying with this code and it doesn't works:

  $(document).on("click", "a", function() { var href = $(this).attr("href"); if(href == 'http://domain.com/test'){ alert('clicked'); } else { alert('not clicked'); } }); 

How do I detect if a specific link is clicked?

Add an event handler to the div click and compare the onclick attribute to your test url.

  $(document).on("click", "div", function() {
      var href = $(this).attr("onclick");
      if(href === "setLocation('http://domain.com/test')"){ 
        alert('clicked'); 
      } else {
        alert('not clicked'); 
      } 
    });

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