我们有
<div class="grandparent">
<div class="parent"><a href="#">a</a></div>
<div class="parent"><a href="#">b</a></div>
<div class="parent"><a href="#">c</a></div>
</div>
将鼠标悬停在我要测试的任何链接上是否有父母&#39;是祖父母的第一个孩子&#39; 如果不是我想申请一个班级
这只是一个简单的例子,我没有在父元素和祖父母元素中有类名
答案 0 :(得分:3)
$(document).on('mouseenter','a',function(){
if($(this).parent().is(':first-child')){
alert('my parent is first child');
} else {
$(this).addClass('myParentIsNot');
}
});
小提琴:
答案 1 :(得分:1)
$('.grandparent > div').hover(function() {
// If the child is NOT the first
if (!$(this).is('div:first-child')) {
$(this).addClass('not-first');
}
});
注意:由于您没有使用类名,因此您必须调整此解决方案以适合您的特定DOM元素。
答案 2 :(得分:1)
如果您只需要设置样式,可以使用CSS和相邻的兄弟选择器(CSS3)
进行设置.grandparent .parent:first-child ~ .parent:hover a {
color: red;
}
答案 3 :(得分:0)
使用jQuery的.index()来测试它在祖父母下面的位置。
$("div.grandparent").on("mouseenter", "div.parent", function(e) {
if($(this).parent(".grandparent").children("div.parent").index(this) > 0) {
$(this).addClass("not-the-first");
}
});
答案 4 :(得分:0)
将元素与:
进行比较$('div > a').mouseover(function () {
if ($(this).parent()[0] !== $('div > div:first')[0]) $(this).addClass('special')
})
<强> jsFiddle example 强>
或者:
$('div > a').mouseover(function () {
if (!$(this).parent().is($('div > div:first'))) $(this).addClass('special')
})
答案 5 :(得分:0)
(function(){
$("div.grandparent div.parent:not(:first-child)").on('mouseover', function(){
$(this).addClass("classHere");
console.log($(this));
});
})();
答案 6 :(得分:0)
你可以使用jquery的.not和:first-child。 http://jsfiddle.net/7wLtY/
$('.parent').not(':first-child').hover(function() {
$( this ).addClass( "not-first-child" );
}, function() {
$( this ).removeClass( "not-first-child" );
});
答案 7 :(得分:0)
可能会这样做:
var $parents = $(".parent"); // cache parents
$("a").hover(function(){
// mouse enters link
var $par = $(this).parent();
if($parents.index($par) !== 0){
$(this).addClass("not-first");
}
}, function(){
// mouse leaves link
$(this).removeClass("not-first");
});