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!
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)
.
使用has()
方法
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
}
});
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.