使用 javascript 在两个之间切换 class

Toggle class using javascript between two

class使用 Javascript 删除 class 的列表不起作用,或者是因为代码中的任何其他错误

代码:http://codepen.io/DPK_RAO/pen/VPXxoJ/

    <ul class="nav">
        <li><a href="#video1" id="link1" class="link1">Video 1</a></li>
        <li><a href="#video2" id="link2" class="link2">Video 2</a></li>
    </ul>

    <div class="video1 active" id="video1">Link 1</div>
    <div class="video2" id="video2">Link 2</div>

CSS:

.video1, .video2{
   display:none;
}

.active{
  display:block;
}

JS

document.getElementById("link1").addEventListner("click", activeVideo1);

function activeVideo1(){
    document.getElementById("video2").classList.remove("active");
    var v1 = document.getElementById("video1");
    v1.className += "active";
}

document.getElementById("link2").addEventListner("click", activeVideo2);

function activeVideo2(){
    document.getElementById("video1").classList.remove("active");
    var v2 = document.getElementById("video2");
    v2.className += "active";
}

您在 addEventListner 中输入错误应该是 addEventListener 请注意 e:

addEventListener
____________^

由于您使用的是 jQuery,它可能就像下面的示例一样简单:

$("#link1").on("click", function(){
    $("#video2").removeClass("active");
    $("#video1").addClass("active");
});

$("#link2").on("click", function(){
    $("#video1").removeClass("active");
    $("#video2").addClass("active");
});
.video1, .video2{
   display:none;
}

.active{
  display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav">
  <li><a href="#video1" id="link1" class="link1">Video 1</a></li>
  <li><a href="#video2" id="link2" class="link2">Video 2</a></li>
</ul>

<div class="video1 active" id="video1">Link 1</div>
<div class="video2" id="video2">Link 2</div>

纯JS解决方案:

document.getElementById("link1").addEventListener("click", function(){
  document.getElementById("video2").classList.remove("active");
  document.getElementById("video1").classList.add("active");
});

document.getElementById("link2").addEventListener("click", function(){
  document.getElementById("video1").classList.remove("active");
  document.getElementById("video2").classList.add("active");
});
.video1, .video2{
display:none;
}

.active{
display:block;
}
<ul class="nav">
  <li><a href="#video1" id="link1" class="link1">Video 1</a></li>
  <li><a href="#video2" id="link2" class="link2">Video 2</a></li>
</ul>

<div class="video1 active" id="video1">Link 1</div>
<div class="video2" id="video2">Link 2</div>

当我 运行 脚本时,我在控制台中收到以下错误:

Uncaught TypeError: document.getElementById(...).addEventListner is not a function

所以您的脚本甚至没有到达 removeClass 函数,它在事件的侦听器部分停止。

你写的函数有错别字。 这是

addEventListener

另注:

替换为:

v1.className += "active";

与:

v1.className += " active"; //added a blank

Updated codepen

你为什么不像

那样添加 class
var v2 = document.getElementById("video2");
v2.classList.add('active');

?