这里有点挣扎。我的eventlistener只检测"已检查"改变我的单选按钮,而不是"未选中"更改。注意:只有纯javascript(vanillajs),没有jQuery。
一个小JSFiddle来解释我的问题:https://jsfiddle.net/kLuba37w/1/
<label class="checkbox checkbox--block">
<input type="radio" name="radio" class="" data-show-more data-target="showmoretarget2" value="1"> <span></span> This is the first radio
</label>
<label class="checkbox checkbox--block">
<input type="radio" name="radio" class="" value="2"> <span></span> This is the second radio
</label>
<div class="js-show-more" data-hook="showmoretarget2">
<h2 class="h2"> Some more content</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis ipsum repellendus, officia dolores consectetur. Error at officiis sequi iure earum.</p>
</div>
JS:
(function() {
"use strict";
var elements = document.querySelectorAll('[data-show-more]');
[].forEach.call(elements, function(element) {
element.addEventListener('change', function(e) {
e.preventDefault();
var target = document.querySelectorAll('[data-hook="' + this.getAttribute('data-target') + '"]')[0];
alert("change detected");
}, false);
});
})();
答案 0 :(得分:1)
这样做的简单方法是使用名称收音机
监听已检查事件的所有单选按钮(function() {
"use strict";
document.querySelector("#radio1").addEventListener("change", function() {
alert("checked radio 1");
});
document.querySelector("#radio2").addEventListener("change", function() {
alert("checked radio 2");
});
})();