2017-10-16 61 views
1

内使用jQuery悬停在某个类我有以下引导4卡:删除引导设置

<div class="card"> 
    <div class="card-body"> 
     <img src="img/person3.jpg" alt="" class="img-fluid rounded-circle w-50 mb-3"> 
     <h3>John Doe</h3> 
     <h5 class="text-muted">Editor</h5> 
     <p class="">Lorem ipsum dolor, sit amet consectetur adipisicing</p> 
     etc... 

的代码的其余部分是不相关的,并且所有的代码按预期工作。不过,我想这样做,只要我将鼠标悬停在卡上,'text-muted'就会从孤立的h5后代中移除。我原本以为我的jQuery的了,所以我尝试了以下内容:

<script> 
    $('.card').hover(function(){ 
     $(this).find('h5').removeClass('.text-muted'); 
    }); 
</script> 

然而,这似乎正好是无所事事的我,我想不通为什么。这应找到覆盖卡的下一个h5后裔,并从中删除相应的text-muted类。在h5之前是否有imgh3兄弟姐妹有这个事实?

我该如何在这里完成我的目标?

+0

'做了me'-究竟什么>你这是什么意思呢?班级没有删除?或者你期望的其他事情? –

+0

我的意思是毫不夸张地说,通过将这个jQuery添加到我的HTML中,没有任何变化。毕竟我在身体关闭标记之前的其他脚本。 –

回答

1

你必须这样做象下面这样: -

$(document).ready(function(){ 
    $('.card').hover(function(){ 
    $('h5', this).removeClass('text-muted'); 
    }, function(e) { 
    $('h5', this).addClass('text-muted'); 
    }); 
}); 

工作例如: -

$(document).ready(function(){ 
 
    $('.card').hover(function(){ 
 
    \t $('h5', this).removeClass('text-muted'); 
 
    }, function(e) { 
 
    $('h5', this).addClass('text-muted'); 
 
    }); 
 
});
.text-muted{ 
 
    color:red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="card"> 
 
    <div class="card-body"> 
 
    <img src="img/person3.jpg" alt="" class="img-fluid rounded-circle w-50 mb-3"> 
 
    <h3>John Doe</h3> 
 
    <h5 class="text-muted">Editor</h5> 
 
    <p class="">Lorem ipsum dolor, sit amet consectetur adipisicing</p> 
 
    </div> 
 
</div>

工作的jsfiddle链接: - https://jsfiddle.net/zuakca4r/

注: - 如果您删除.'.text-muted'(在removeClass()使用)

您的代码也能工作。

检查: - https://jsfiddle.net/fc89fmys/

+0

宾果。删除找到了诀窍。为什么发现不起作用? –

+0

@JohnnyApple如果你从''.text-muted''(用在'removeClass()'中)中删除'.',你的代码也会工作。检查这个: - https://jsfiddle.net/fc89fmys/ –

0

在document.ready函数内传递代码。

<script> 
    $(document).ready(function(e) { 
     $('.card').hover(function(e){ 
     $(this).find('h5').removeClass('text-muted'); 
     }, function(e) { 
     $(this).find('h5').addClass('text-muted'); 
     }); 
    }); 
</script> 
+0

使用您的确切代码没有视觉变化。我也从来不需要文档就绪函数来将我的jQuery放在我目前的工作流程下(使用Bootstrap 4 Git Starter Pack和NPM)。 –

0

当您使用removeClass功能,不包括 ''。所以它应该是

$(document).ready(function() { 
    $('.card').hover(function() { 
     $(this).find('h5').removeClass('text-muted'); 
    }); 
}) 

如果您想在鼠标离开时添加该类,请尝试使用此代码。

$(document).ready(function() { 
    $('.card').hover(function() { 
     $(this).find('h5').removeClass('text-muted'); 
    }); 

    $('.card').mouseenter(function() { 
     $(this).find('h5').removeClass('text-muted'); 
    }); 

    $('.card').mouseleave(function() { 
     $(this).find('h5').addClass('text-muted'); 
    }); 
}) 

你可以在这里检查此https://codepen.io/anon/pen/ZXqjrK