简体   繁体   English

我无法添加或删除课程

[英]I can't add or remove a class

I am trying to remove a class and add a class within one function.我正在尝试删除一个类并在一个函数中添加一个类。 But when I click on the button nothing is happening.但是当我点击按钮时什么也没有发生。

This is my code这是我的代码

 function unlikeVerhaal(unlike) { unlike.preventDefault; document.querySelector('#unliked').classList.add('onzichtbaar'); document.querySelector('#liked').classList.remove('onzichtbaar'); } document.querySelector('.likebutton').addEventListener('submit', unlikeVerhaal);
 .onzichtbaar { display: none; }
 <li> <button type="submit" class="likebutton"> <img src="icons/lined.png" alt="lined heart" class="unliked" id="unliked"> <img src="icons/solid.png" alt="solid heart" id="liked" class="onzichtbaar"> </button> 777 </li>

What I am trying to get is that the class is added to the first image and removed by the second image.我想要得到的是该类被添加到第一个图像并被第二个图像删除。

You just need to use a combination of the three methods .contains() , .add() and .remove() from the element.classList property along with a simple if/else statement (or a ternary operator if you prefer that) as can be seen in the Code Snippet below:您只需要使用element.classList属性中的三种方法.contains().add().remove()的组合以及一个简单的if/else statement (或三元运算符,如果您愿意的话)作为可以在下面的代码片段中看到:

 var btn = document.querySelector('.likebutton'); function unlikeVerhaal() { var ul = document.getElementById("unliked"); var l = document.getElementById("liked"); if (ul.classList.contains("onzichtbaar")) { ul.classList.remove("onzichtbaar"); l.classList.add("onzichtbaar"); console.log("Inspect your elements to see the class switching!") } else { l.classList.remove("onzichtbaar"); ul.classList.add("onzichtbaar"); console.log("Inspect your elements to see the class switching!") } } btn.addEventListener("click", unlikeVerhaal)
 .onzichtbaar {background-color: green;}
 <li> <button type="button" class="likebutton"> <div class="unliked" id="unliked">A</div> <div id="liked" class="onzichtbaar">B</div> </button> 777 </li>


You can either inspect the elements to see the class switching between the two or you can just watch the green background styling which is applied to an element with the onzichtbaar class name switching between the two.您可以检查元素以查看两者之间的类切换,或者您可以仅观看应用于具有onzichtbaar类名称的元素在onzichtbaar之间切换的绿色背景样式

This will works as you expect:这将按您的预期工作:

function unlikeVerhaal(e) {
    e.preventDefault;
    document.getElementById('unliked').classList.add('onzichtbaar');
    document.getElementById('liked').classList.remove('onzichtbaar'); 
} 

document.getElementById('likebutton').addEventListener('click', unlikeVerhaal);

Just change submit to click and remove type from button只需将submit更改为click并从按钮中删除type

Fiddle小提琴

Update:更新:

Updated fiddle更新的小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM