当单选按钮选中 vanilla js 时显示 div

War*_*sse 2 javascript forms radio-button

这里有点挣扎。我的事件侦听器仅检测到我的单选按钮的“已选中”更改,而不是“未选中”更改。注意:只有纯 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>
Run Code Online (Sandbox Code Playgroud)

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);

  });

 })();
Run Code Online (Sandbox Code Playgroud)

Pro*_*r08 5

执行此操作的简单方法是收听已检查事件和名称为 radio 的所有单选按钮

(function() {
  "use strict";

    document.querySelector("#radio1").addEventListener("change", function() {
        alert("checked radio 1");
    });

    document.querySelector("#radio2").addEventListener("change", function() {
        alert("checked radio 2");
    });

})();
Run Code Online (Sandbox Code Playgroud)