【问题标题】:Combining javascript code with different selector IDs correctly正确组合具有不同选择器 ID 的 javascript 代码
【发布时间】:2021-04-18 09:34:07
【问题描述】:

我在下面提供了大约 30 个具有不同 ID 的选择器示例代码

document.getElementById("selector-1").onchange = function() {
  document.getElementById("btn-1").href = "/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

document.getElementById("selector-2").onchange = function() {
  document.getElementById("btn-2").href = "/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

document.getElementById("selector-3").onchange = function() {
  document.getElementById("btn-3").href = "/?add-to-cart=" + this.selectedOptions[0].getAttribute('data-product') + "&" + "variation_id=" + this.value + "/";
}

能否请您告诉我如何将所有这些组合成更通用的东西,以免每次都使用不同的 ID 带来所有代码,因为我看到目前这是非常未优化的代码。不幸的是,我的知识不足以将其重构为更有效的东西。 谢谢各位。

【问题讨论】:

    标签: javascript jquery jquery-selectors


    【解决方案1】:

    没有看到 HTML(例如,我可以使用 closest),您可以尝试从最近的静态容器委托(这里我必须再次使用文档,因为我没有看到您的 HTML)

    document.addEventListener("change", function(e) {
      const tgt = e.target;
      if (tgt.id.startsWith("selector-")) {
        const id = tgt.id.replace("selector-", "btn-");
        document.getElementById(id).href = "/?add-to-cart=" + tgt.selectedOptions[0].getAttribute('data-product') + "&variation_id=" + tgt.value + "/";
      }
    })
    

    或者在点击时获取值:

    document.addEventListener("click", function(e) {
      const tgt = e.target;
      if (tgt.id.startsWith("btn-")) {
        const id = tgt.id.replace("btn-", "selector-");
        const sel = document.getElementById(id);
        tgt.href = "/?add-to-cart=" + sel.selectedOptions[0].getAttribute('data-product') + "&variation_id=" + sel.value + "/";
      }
    })
    

    【讨论】:

      【解决方案2】:

      您可以使用文档查询选择器根据给定属性的存在或值(包括 ID)来匹配元素。由于使用简单的 css 匹配,所有功能都是相同的,例如:

      console.log(Array.from(document.querySelectorAll("div[id^='selector']")));
      <div id="selector-1">1</div>
      <div id="selector-2">2</div>
      <div id="selector-3">3</div>

      然后遍历数组以将您想要的内容添加到元素中就足够了。

      【讨论】:

      猜你喜欢
      • 2011-02-02
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      相关资源
      最近更新 更多