将javascript代码与不同的选择器ID正确组合

将javascript代码与不同的选择器ID正确组合,javascript,jquery,jquery-selectors,Javascript,Jquery,Jquery Selectors,我有大约30个选择器,具有不同的ID示例代码,我在下面提供了这些代码 document.getElementById(“选择器-1”).onchange=function(){ document.getElementById(“btn-1”).href=“/?添加到购物车=“+this.selectedOptions[0]。getAttribute('data-product')+”&“+”变体_id=“+this.value+”/”; } document.getElementById(“选择

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

document.getElementById(“选择器-1”).onchange=function(){
document.getElementById(“btn-1”).href=“/?添加到购物车=“+this.selectedOptions[0]。getAttribute('data-product')+”&“+”变体_id=“+this.value+”/”;
}
document.getElementById(“选择器-2”).onchange=function(){
document.getElementById(“btn-2”).href=“/?添加到购物车=“+this.selectedOptions[0]。getAttribute('data-product')+”&“+”变体_id=“+this.value+”/”;
}
document.getElementById(“选择器-3”).onchange=function(){
document.getElementById(“btn-3”).href=“/?添加到购物车=“+this.selectedOptions[0]。getAttribute('data-product')+”&“+”变体_id=“+this.value+”/”;
}
您能告诉我如何将所有这些结合到更通用的东西中,这样就不会每次都使用不同的ID带来所有代码,因为我看到这是目前非常未优化的代码。不幸的是,我的知识不足以将其重构为更有效的东西。 谢谢大家。

看不到HTML(因此我可以使用
最近的
例如),您可以尝试从最近的静态容器中委派(这里我必须使用文档,因为我看不到您的HTML)

document.addEventListener(“更改”,函数(e){
常数tgt=e.target;
if(tgt.id.startsWith(“选择器-”){
const id=tgt.id.replace(“选择器-”,“btn-”);
document.getElementById(id).href=“/?添加到购物车=“+tgt.selectedOptions[0]。getAttribute('data-product')+”&variation_id=“+tgt.value+”/”;
}
})
或者,单击即可获取值:

document.addEventListener(“单击”),函数(e){
常数tgt=e.target;
if(tgt.id.startsWith(“btn-”){
const id=tgt.id.replace(“btn-”,“选择器-”;
const sel=document.getElementById(id);
tgt.href=“/?添加到购物车=“+sel.selectedOptions[0]。getAttribute('data-product')+”&variation_id=“+sel.value+”/”;
}
})
看不到HTML(例如,我可以使用
最近的
),您可以尝试从最近的静态容器委派(这里我必须使用文档,因为我看不到您的HTML)

document.addEventListener(“更改”,函数(e){
常数tgt=e.target;
if(tgt.id.startsWith(“选择器-”){
const id=tgt.id.replace(“选择器-”,“btn-”);
document.getElementById(id).href=“/?添加到购物车=“+tgt.selectedOptions[0]。getAttribute('data-product')+”&variation_id=“+tgt.value+”/”;
}
})
或者,单击即可获取值:

document.addEventListener(“单击”),函数(e){
常数tgt=e.target;
if(tgt.id.startsWith(“btn-”){
const id=tgt.id.replace(“btn-”,“选择器-”;
const sel=document.getElementById(id);
tgt.href=“/?添加到购物车=“+sel.selectedOptions[0]。getAttribute('data-product')+”&variation_id=“+sel.value+”/”;
}
})

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

console.log(Array.from(document.querySelectorAll(“div[id^='selector']))
1
2.

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

console.log(Array.from(document.querySelectorAll(“div[id^='selector']))
1
2.
3
我强烈建议我强烈建议