【问题标题】:How to hide a whole component on selecting a radio button如何在选择单选按钮时隐藏整个组件
【发布时间】:2022-01-08 15:27:14
【问题描述】:

我正在处理 html 文件。我有两个两个标签(比如 L1 和 L2)。每个标签都有两个单选按钮。如果用户从 L1 中选择任何单选按钮,我想隐藏 L2 和它的单选按钮。

我知道这可以使用 java 脚本来完成,但是如何捕获我可以执行我的 java 脚本的单选按钮的选择。

【问题讨论】:

  • 您能否提供一个minimal reproducible example 来展示您迄今为止所做的尝试,或者至少提供您想要采取行动的标记?

标签: javascript html radio-button xhtml


【解决方案1】:

我已根据您的问题准备了一个版本。这是你的意思吗?

[HTML]

<div id="container" class="container">
    <div id="first-radio">
       <label for="L1">L1</label>
  <div class="radio-box">
    <input type="radio" name="L1" /> L1-first
  </div>
  <div style="margin-bottom: 15px" class="radio-box">
    <input type="radio" name="L1" /> L1-second
  </div> 
    </div>
  
    <div id="second-radio">
        <label for="L2">L2</label>
  <div class="radio-box">
    <input type="radio" name="L2" /> L2-first
  </div>
  <div class="radio-box">
    <input type="radio" name="L2" /> L2-second
  </div>
    </div>

[Javascript]

const container = document.getElementById("container");
const firstRadio = document.getElementById("first-radio");
const secondRadio = document.getElementById("second-radio");
const L1_Radio1 = container.children[0].children[1];
const L1_Radio2 = container.children[0].children[2];
const L2_Radio1 = container.children[1].children[1];
const L2_Radio2 = container.children[1].children[2];

const array1 = [L1_Radio1, L1_Radio2];
const array2 = [L2_Radio1, L2_Radio2];

function hideRadio() {
    array1.forEach(item => {
        item.addEventListener("change", () => {
            secondRadio.style.visibility = "hidden";
        });
    });

    array2.forEach(item => {
        item.addEventListener("change", () => {
            firstRadio.style.visibility = "hidden";
        });
    });
}

hideRadio();

你可以在这里观看它的实际操作:https://jsfiddle.net/s4onh9qk/6/

【讨论】:

  • 仅供参考,您可以做一个 sn-p 而不是花时间制作一个 jsfiddle ;)
  • 我认为这样更能说明问题,但感谢您的提示! :))
  • 我的意思是,一个可以与 jsfiddle 完全一样运行的 sn-p,所以它也很有说明性! :) 它只是直接包含在 SO 的帖子中,所以更容易使用
  • 是的,我已经知道你的意思了。谢谢! :)) 虽然 jsfiddle 也没有太多额外的工作。
猜你喜欢
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多