[英]How To Use An onclick Function To Check Class Name Without jQuery
I am looking to check if a element has a class name on click. 我想检查一个元素是否有点击类名。 I have the click event calling the function but nothing logs to the console.
我有click事件调用函数但没有任何日志记录到控制台。 Interestingly, document.write works but no matter what I click, it logs the else even if the HTML element has the class name.
有趣的是,document.write有效但无论我点击什么,即使HTML元素具有类名,它也会记录else。
HTML HTML
<p>What is 2+2?</p>
<a href="#" class="answer wrong">5</a>
<a href="#" class="answer correct">4</a>
<a href="#" class="answer wrong">7</div>
<a href="#" class="answer wrong">2</div>
CSS CSS
var wrongMsg = "Sorry, that's not the answer"
var correctMsg = "Correct!"
var answers = document.getElementsByClassName("answer");
for (var i=answers.length; i--;){
answers[i].addEventListener('click', checkMulti);
};
function checkMulti(){
if ( this.className == "correct" ){
console.log(correctMsg);
}else{
console.log(wrongMsg);
}
}
You need to use the method contains
from classList
. 您需要使用
contains
在classList
的方法。
var wrongMsg = "Sorry, that's not the answer" var correctMsg = "Correct!" var answers = document.getElementsByClassName("answer"); for (var i = answers.length; i--;) { answers[i].addEventListener('click', checkMulti); }; function checkMulti() { if (this.classList.contains("correct")) { console.log(correctMsg); } else { console.log(wrongMsg); } }
<p>What is 2+2?</p> <a href="#" class="answer wrong">5</a> <a href="#" class="answer correct">4</a> <a href="#" class="answer wrong">7</div> <a href="#" class="answer wrong">2</div>
I believe correct approach would you to look for correct
classname in element's classList
property 我相信你会在element的
classList
属性中寻找correct
classname
like so: this.classList.contains("correct");
像这样:
this.classList.contains("correct");
more information: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList 更多信息: https : //developer.mozilla.org/en-US/docs/Web/API/Element/classList
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.