用於顯示HTML範圍滑桿值的JS對於第一個項目(A1)運作良好。然而,我也想將其用於A2項目(實際上有20個項目,所以需要重複使用19次)。是否有一種方法可以為多個迭代編寫程式碼?
const slideValue = document.querySelector("span"); const inputSlider = document.querySelector("input"); inputSlider.oninput = (()=>{ let value = inputSlider.value; slideValue.textContent = value; slideValue.style.left = (value/.1) + "%"; slideValue.classList.add("show"); }); inputSlider.onblur = (()=>{ slideValue.classList.remove("show"); });
<body> <div class="itemstatement">A1. Blah Blah Blah.</div> <div class="range"> <div class="sliderValue"><span>0</span></div> <div class="field"> <div class="value left">0</div> <input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1"> <div class="value right">10</div> </div></div> <div class="itemstatement">A2. Blah Blah Blah.</div> <div class="range"> <div class="sliderValue"><span>0</span></div> <div class="field"> <div class="value left">0</div> <input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1"> <div class="value right">10</div> </div></div></div></body>
P粉6800005552023-09-13 00:49:21
當然有。你會很容易地辨識出你自己的程式碼,它被包裹在一個for迴圈內。
var elems = document.querySelectorAll(".range"); elems.forEach(function(elem) { const slideValue = elem.querySelector("span"); const inputSlider = elem.querySelector("input"); inputSlider.oninput = (() => { let value = inputSlider.value; slideValue.textContent = value; slideValue.style.left = (value / .1) + "%"; slideValue.classList.add("show"); }); inputSlider.onblur = (() => { slideValue.classList.remove("show"); }); })
<div class="itemstatement">A1. Blah Blah Blah.</div> <div class="range"> <div class="sliderValue"><span>0</span></div> <div class="field"> <div class="value left">0</div> <input type="range" id="A1" name="A1" min="0" max="10" value="0" steps="1"> <div class="value right">10</div> </div> </div> <div class="itemstatement">A2. Blah Blah Blah.</div> <div class="range"> <div class="sliderValue"><span>0</span></div> <div class="field"> <div class="value left">0</div> <input type="range" id="A2" name="A2" min="0" max="10" value="0" steps="1"> <div class="value right">10</div> </div> </div>