jQuery check if target is link

会有一股神秘感。 提交于 2020-04-08 04:55:22

问题


I have a global function to capture clicks.

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

I want to do additional stuff when the target is a link, but if the the <a> tag actually surrounds a div (as HTML5 allows this) the target will be that div.

http://jsfiddle.net/Af37v/


回答1:


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');
    }
});



回答2:


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.




回答3:


Try this

$(document).click(function(e){
  //do something
  if($(this).closest('a').length)
    //do something
});



回答4:


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




回答5:


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
  }
});



回答6:


Updated: You could check if the target is an a or if a parent is an a.

$(function () {
    $(document).on('click', function (e) {
        $target = $(e.target);
        if ($target.closest('a').length > 0) {
            alert('i am an a');
        }
    });
});

http://jsfiddle.net/8jeGV/4/




回答7:


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
    }
});


来源:https://stackoverflow.com/questions/14327489/jquery-check-if-target-is-link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!