【问题标题】:How to refactor my code so it's not repeating the same thing如何重构我的代码以使其不重复相同的事情
【发布时间】:2022-12-06 02:31:28
【问题描述】:

我的页面上有 3 个不同的按钮,当您单击其中一个按钮时,它会检查相应的单选按钮。

目前,我的每个按钮都有自己的 onclick 功能:

onclick="radioChecked1()"
onclick="radioChecked2()"
onclick="radioChecked2()"

然后是功能:

function radioChecked1() {
  var package1 = document.querySelector("#package1");
  package1.setAttribute("checked", 1);
}
function radioChecked2() {
  var package2 = document.querySelector("#package2");
  package2.setAttribute("checked", 1);
}
function radioChecked3() {
  var package3 = document.querySelector("#package3");
  package3.setAttribute("checked", 1);
}

这些函数做同样的事情,唯一改变的是它选择的输入的 id 中的数字。
我确定有一种方法可以将其简化为一个功能,而不是每个按钮都有一个单独的功能,我不知道该怎么做。

【问题讨论】:

  • 你能显示这个的html吗?所以我/我们可以看到整个设置......

标签: javascript function refactoring


【解决方案1】:

您可以通过简化函数和使用参数来重构此代码:

function radioChecked(id) {
    var package = document.querySelector(id);
    package.setAttribute("checked", 1);
}

然后在您的按钮上调用具有相应 ID 的函数:

onclick="radioChecked('#package1')" onclick="radioChecked('#package2')" onclick="radioChecked('#package3')"

【讨论】:

    【解决方案2】:

    这在一定程度上取决于您的标记是如何编写的,但是如果您将 data attributes 添加到按钮和单选按钮,您可以在单击按钮时从按钮中获取 id,然后在单选输入上找到相应的 id。

    在这里,我将按钮和无线电输入包装在它们自己的容器中,以便我可以使用 event delegation - 将一个侦听器添加到父容器,当它们在 DOM 中冒泡时从其子元素捕获事件,而不是将侦听器附加到全部的元素。

    // Instead of inline JS we cache the containers elements
    // and then add one listener to the buttons container
    const radios = document.querySelector('.radios');
    const btns = document.querySelector('.btns');
    btns.addEventListener('click', handleClick);
    
    // If the clicked element is a button
    // extract its id from its dataset, look for
    // the corresponding radio input, and update the
    // `checked` property
    function handleClick(e) {
      if (e.target.matches('button')) {
        const { id } = e.target.dataset;
        const radio = radios.querySelector(`[data-id="${id}"]`);
        radio.checked = true;
      }
    }
    fieldset { margin-top: 1em; }
    <fieldset class="btns">
      <legend>Buttons</legend>
      <button data-id="radio1" type="button">Button 1</button>
      <button data-id="radio2" type="button">Button 2</button>
      <button data-id="radio3" type="button">Button 3</button>
    </fieldset>
    
    <fieldset class="radios">
      <legend>Radio buttons</legend>
      <label for="radio1">Radio1
        <input data-id="radio1" type="radio" name="radioset">
      </label>
      <label for="radio2">Radio2
        <input data-id="radio2" type="radio" name="radioset">
      </label>
      <label for="radio3">Radio3
        <input data-id="radio3" type="radio" name="radioset">
      </label>
    </fieldset>

    附加文件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多