Check if event target is hyperlink

前端 未结 3 907
长情又很酷
长情又很酷 2021-02-02 06:09

I have a large div inside there which are smaller divs, achor tags and other elements. Each large div in my program is bound to \"mousedown\" event and inside the onMouseDown ha

相关标签:
3条回答
  • 2021-02-02 06:44

    I tried modifying your code and there were multiple problems with the code and corrected them.

    This is the JavaScript part

    var src = '<div class="camp-name"><span class="btnCampaign"><div class=""></div></span><span class="campaign-name"><a href="http://www.google.com">Some Link here</a></span></div>';
    
    var label = document.createElement('DIV')
    label.innerHTML = src;
    var topdiv = document.getElementById("test");
    console.log(label)
    topdiv.appendChild(label);
    
    label.addEventListener('click', test, false);
    
    function test(event) {
        if(event.target.tagName.toLowerCase() === 'a') {
            var href = event.target.href;
            console.log(href);
        }
        window.location = href;
    };
    

    This is the HTML part of it

    <div id="test">
     test
    </div>
    

    I did this in a jsfiddle http://jsfiddle.net/KDejm/1/

    Please let me know if the vent is captured correctly.

    0 讨论(0)
  • 2021-02-02 06:53

    You could check the tagName property, as said by @parthik-gosar. Another way is to use the instanceof operator to check the element class (hyperlinks are of type HTMLAnchorElement):

    if (event.target instanceof HTMLAnchorElement) {
      console.log(event.target.href);
    }
    
    0 讨论(0)
  • 2021-02-02 06:58

    You should get it through

    if(event.target.tagName.toLowerCase() === 'a')
    {
        event.target.href; //this is the url where the anchor tag points to.
    }
    
    0 讨论(0)
提交回复
热议问题