【发布时间】:2018-06-08 04:21:01
【问题描述】:
我有一个单选按钮列表。
<input type="radio" name="capital" value="bratislava">
<input type="radio" name="capital" value="kiev">
<input type="radio" name="capital" value="prague">
在单选按钮事件侦听器类型 change 我添加一些 class 这样的名称。
// Scope toggles
var toggles = document.querySelectorAll('input[type=radio]');
// Accesses the toggles length property outside the loop and make the loop run faster
var tL = toggles.length;
// Loop-in for `toggles` length HTML collection
for (var i = 0; i < tL; i++) {
// Store array-like objects in this variable
var currentToggle = toggles[i];
// Run event listener method on `change` and refer to element using `this` keyword
currentToggle.addEventListener('change', function() {
// + ADD CLASS NAME
// Check if element is checked and if className isn't present
if ( this.checked && !this.className.match(/(?:^|\s)class(?!\S)/) ) {
// Add class name without removing/affecting existing values
this.className += " class";
}
// - REMOVE CLASS NAME
else {
// Replace class with empty string
this.className = this.className.replace( /(?:^|\s)class(?!\S)/g , '' );
}
})
}
这适用于复选框元素,但不适用于单选按钮组。 目标在这个问题的标题中。
为了解决这个问题,我假设我应该在 if 语句中设置另一个循环,并为所有未检查的无线电循环并删除该类?
【问题讨论】:
-
为单选按钮添加“点击”事件的监听器,而不是“更改”。
-
单选按钮仅支持两个事件:
change和input。 -
这似乎是一个更接近您的问题。看一看;希望它有所帮助! stackoverflow.com/questions/8838648/…
标签: javascript