最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if jQuery clicked element an anchor containing an img - Stack Overflow

programmeradmin5浏览0评论

How can I check if the clicked element was an anchor containing an img?

So for example I want to check if this element was clicked:

<a href="#">
    <img src="#" />
<a/>
jQuery(document).click(function(e) {
    // e.target.hereIsWhereINeedHelp;
});

Thanks in advance!

How can I check if the clicked element was an anchor containing an img?

So for example I want to check if this element was clicked:

<a href="#">
    <img src="#" />
<a/>
jQuery(document).click(function(e) {
    // e.target.hereIsWhereINeedHelp;
});

Thanks in advance!

Share Improve this question edited Apr 15, 2015 at 15:58 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Apr 15, 2015 at 15:53 user1878980user1878980 5212 gold badges8 silver badges22 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 8

If you wish to capture the "click" from any element:

jQuery(document).click(function(e) {
    if (jQuery(e.target).is('a') && jQuery(e.target).has('img')) {
        // code goes here
    }    
});

Whether you choose to prevent the "default behavior" is another question.

You can use .is("a") and .has("img"):

<a href="#">
   <img src="#" />
<a/>

<script>
    jQuery(document).click(function(e) {
        var target = $( e.target );
        if ( target.is( "a" ) && target.has("img") ) {
            //Do what you want to do
        }
    });
</script>

You can use the has() method to check if an element contains another:

$('a').click(function(e) {
    e.preventDefault(); // this will stop the link from going anywhere.
    if ($(this).has('img')) {
        // do something
    }
});

You could also use if ($(this).find('img').length).

Use has() method

this.has("img");

You can use has() or find()

$("a").on("click", function(e) {

    e.preventDefault(); // Prevents the link redirection

    if ( $(this).has("img") ) {
        console.log("has image");
    }

});

Just check if the clicked element is an anchor tag using is, and then use find to look for an image. If both are true then you //do something.

jQuery(document).click(function() {
    var el = $(this);
    if(el.is("a") && el.find("img").length > 0){
        //do something
    }
});
发布评论

评论列表(0)

  1. 暂无评论