我有一个单选按钮列表。从取消选中的单选按钮删除班级名称
<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'。 –
这似乎更接近你的问题。看一看;希望它是帮助! https://stackoverflow.com/questions/8838648/onchange-event-handler-for-radio-button-input-type-radio-doesnt-work-as-one –