jQuery check if target is link

后端 未结 7 1386
傲寒
傲寒 2021-02-07 23:49

I have a global function to capture clicks.

$(document).click(function(e){
  //do something
  if(clickedOnLink)
    //do something
});

I want t

相关标签:
7条回答
  • 2021-02-08 00:02

    You can test if there's a <div> under <a> by testing if the .children() <div> has anything inside it. If nothing is inside, or there is no <div>, the if statement will return false.

    I suggest this code:

    $(document).click(function(e){
        var willRedirect = ($('a[href="/"]').attr('href').indexOf('#') == -1 ? true : false),
    
        //run code
    
        if ( willRedirect === false ){
            e.preventDefault();
    
            //the link will not redirect
    
            if ( $(this).children('div').html() ){
                //there is a <div> inside <a> containing something
            }
            else {
                //there is no <div> inside <a>
            }
        }
        else {
            //the link is not pointing to your site
        }
    });
    
    0 讨论(0)
  • 2021-02-08 00:06

    Try this

    $(document).click(function(e){
      //do something
      if($(this).closest('a').length)
        //do something
    });
    
    0 讨论(0)
  • 2021-02-08 00:14

    If the exact target is link, then you can use .is()

    Example:

    $(".element").on("click", function(e){
      if($(e.target).is("a")){
        //do your stuff
      }
    });
    

    EDIT:

    If it is surrounded by other element that is inside an anchor tag, then you can use closest() and check whether it have anchor tag parent or not by using length

    Example:

    $(".element").on("click", function(e){
      if($(e.target).closest("a").length){
        //do your stuff
      }
    });
    
    0 讨论(0)
  • 2021-02-08 00:15

    You can try to see if the element you clicked on either is or is a child of an <a> tag.

    $(document).click(function(e){
        if($(e.target).closest('a').length){
            alert('You clicked a link');
        }
        else{
            alert('You did not click a link');
        }
    });
    
    0 讨论(0)
  • 2021-02-08 00:20

    With jquery just get the tagName attribute $("a").prop("tagName");

    0 讨论(0)
  • 2021-02-08 00:26

    I believe using is will actually have better performance than the answers suggesting closest:

    $(e.target).is('a, a *');
    

    This checks if the element itself is an a or if it is contained with an a.

    This should be faster than closest because it will use matches on the element itself and not need to traverse up the DOM tree as closest will do.

    0 讨论(0)
提交回复
热议问题