我有大约30个具有不同I的选择器,我在下面提供了示例代码
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 + "/";
}你能告诉我如何将所有这些合并成更通用的东西,这样就不会每次都用不同的is带来所有的代码,因为我看到这是目前非常未优化的代码。不幸的是,我的知识不足以将其重构为更有效的东西。谢谢大家。
发布于 2021-01-13 19:19:43
看不到超文本标记语言(例如,我可以使用closest )你可以尝试从最近的静态容器中委托(这里我不得不使用文档,因为我没有看到你的超文本标记语言)
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 + "/";
}
})发布于 2021-01-13 19:21:04
您可以使用文档查询选择器根据给定属性的存在或值匹配元素,包括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>
然后对数组进行迭代,将您想要的内容添加到元素中应该就足够了。
https://stackoverflow.com/questions/65700792
复制相似问题