Javascript 多个悬停切换类只工作一次

Javascript 多个悬停切换类只工作一次,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我正试图在悬停时显示/隐藏一个div。我的代码适用于列表中的第一项,但不适用于其他项 HTML jQuery $("#track").hover(function () { var thisvideo = $(this).attr('name'); $(thisvideo).toggleClass("on"); }); $(".ani").hover(function () { var thisvideo = $(this).attr('name'); $(th

我正试图在悬停时显示/隐藏一个div。我的代码适用于列表中的第一项,但不适用于其他项

HTML

jQuery

$("#track").hover(function () {
    var thisvideo = $(this).attr('name');
    $(thisvideo).toggleClass("on");
});
$(".ani").hover(function () {
    var thisvideo = $(this).attr('name');
    $(thisvideo).toggleClass("on");
});

在jquery中,只需将#track by.ani替换为元素的类即可。

更改为

<div class="track" class="ani" name="#tomday">
        <h1>listen</h1>
        <h2>who we want to be</h2>
    </div>
    <div class="track" class="ani" name="#tomday">
        <h1>listen</h1>
        <h2>who we want to be</h2>
    </div>
    <div class="clear"></div>
    <div id="tomday" class="video off"></div>
JS:

任何id都必须是唯一的。如果您想在多个地方使用它,只需将其设置为类即可;)

这是您的演示

HTML

jQuery

$("#track").hover(function () {
    var thisvideo = $(this).attr('name');
    $(thisvideo).toggleClass("on");
});
$(".ani").hover(function () {
    var thisvideo = $(this).attr('name');
    $(thisvideo).toggleClass("on");
});

你不能重复使用ID(#track),而是使用类。我的荣幸。。!如果这个答案对你有帮助,你可以接受:)
$(".track").hover(function() {
            var thisvideo = $(this).attr('name');
            $(thisvideo).toggleClass("on");
        });
<div id="track" class="ani" name="#tomday">
        <h1>listen</h1>
        <h2>who we want to be</h2>
</div>
<div id="track2" class="ani" name="#next">
        <h1>next</h1>
        <h2>thing</h2>
</div>
<div class="clear"></div>
<div id="tomday" style="" class="video off"></div>
<div id="next" style="" class="video off"></div>
.off {
    display:none;
}
.on {
    display:block;
}
.clear:after {
    clear:both;
}
.ani {
    transition:1s;
}
.invisible {
    color:transparent;
}
#track, #track2 {
    margin:12% 1% 1% 1%;
    height:12%;
    width:12%;
    color:rgba(211, 50, 9, 0.05);
    float:left;
}
#track:hover, #track2:hover {
    margin-top:15%;
    color:rgba(211, 50, 9, 1)
}
.video {
    height:100%;
    width:100%;
    position:fixed;
    top:0;
    left:0;
    z-index:-1;
    background:red;
    opacity:0.5;
}
$(".ani").hover(function () {
    var thisvideo = $(this).attr('name');
    $(thisvideo).toggleClass("on");
});