在一个简单的问题上遇到了麻烦。我的早茶不够浓。
如果 div 有一个 child ,那就是 anchor THEN-等等。不想向 .box 添加额外的类
类似于:
$('.box').click(function(){
if ($(this).children('a')) {
//some thing
} else {
//some thing else
}
});
<div class="box"><a href="#"><img src="#" /></a></div>
<div class="box"><img src="#" /></div>
<div class="box"><img src="#" /></div>
最佳答案
检查 length
属性:
$('.box').click(function(){
if ($(this).children('a').length) {
//some thing
} else {
//some thing else
}
});
因为 children
方法(像大多数 jQuery 方法一样)返回一个 jQuery 实例,它总是评估为 true
(所以你总是以 如果
分支)。 length
属性返回一个数字,如果它是 0
,它将计算为 false
。
关于jQuery 如果 div 有 anchor child 那么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9538397/