如何将这段jQuery代码转换为JavaScript?
$('#element').click(function(){
$(this).toggleClass('class1 class2')
});
我已经尝试过以下代码,但无济于事.
第一个是:
var element = document.getElementById('element'),classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
if (classNum === 0) {
this.classList.remove("class1");
this.classList.add("class2");
classNum = 1;
}
else if (classNum === 1) {
this.classList.remove("class2");
this.classList.add("class1");
classNum = 0;
}
}
第二个是:
var element = document.getElementById('element'),classNum = 0; // Supposing I know that the first time there will be that class
element.onmousedown = function() {
if (classNum === 0) {
this.className -= "class1";
this.classList += "class2";
classNum = 1;
}
else if (classNum === 1) {
this.classList -= "class2";
this.classList += "class1";
classNum = 0;
}
}
任何不建议我坚持使用jQuery的答案将不胜感激.
[编辑]
我已经尝试了所有的解决方案,但未能做到正确.我相信这是因为我没有明确说明该元素有多个类,如下所示:
class="class1 class3 class4"
我想要的基本上是用class2替换class1并在它们之间切换.