我有一个单选按钮列表。
<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语句和循环中设置另一个循环并删除该类?
答案 0 :(得分:1)
是的,添加第二个循环将解决您的问题
var varName = document.querySelectorAll('input[type="radio"]');
for (var i = 0; i < varName.length; i++) varName[i].onchange = functionName;
function functionName() {
for (var i = 0; i < varName.length; i++) {
if (varName[i] == this) varName[i].classList.add('selected');
else varName[i].classList.remove('selected');
}
}
&#13;
.selected {
background-color: green;
}
&#13;
<input type="radio" name="capital" value="bratislava">
<input type="radio" name="capital" value="kiev">
<input type="radio" name="capital" value="prague">
&#13;
答案 1 :(得分:1)
在评论中提到的帖子[OnChange event handler for radio button (INPUT type="radio") doesn't work as one value之后,您可以在不循环输入的情况下完成此操作。
// 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;
var last = undefined;
// 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 to current
// 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";
}
if(last === undefined){
last = this;
return;
}
// - REMOVE CLASS NAME
else {
// Replace class with empty string
last.className = last.className.replace( /(?:^|\s)class(?!\S)/g , '' );
last = this;
}
})
}
<input type="radio" name="capital" value="bratislava">bratislava
<input type="radio" name="capital" value="kiev">kiev
<input type="radio" name="capital" value="prague">prague