如何在網站上顯示輸入值?我已經嘗試顯示它,但是當我更改輸入的值時,顯示仍然相同。
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
valueInp.innerHTML = rangeInput.value;
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
uj5u.com熱心網友回復:
如果<p>值的元素將始終緊跟在您的范圍元素之后,那么以下腳本將處理任意數量的范圍/值組合:
document.querySelectorAll(".range")
.forEach(r=>r.addEventListener("input",update(r)));
function update(r){
const ur= ()=>r.nextElementSibling.textContent=r.value;
ur();
return ur;
}
<input type="range" min="1" max="100" value="40" step="1" class="range"/>
<p></p>
<input type="range" min="1" max="100" value="20" step="1" class="range"/>
<p></p>
<input type="range" min="1" max="100" value="30" step="1" class="range"/>
<p></p>
uj5u.com熱心網友回復:
您所做的將加載段落中的輸入值。另外,您需要一個 EventListener 來跟蹤輸入更改,如下所示:
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
valueInp.innerHTML = rangeInput.value;
rangeInput.addEventListener("input", ()=>{
valueInp.innerHTML = rangeInput.value;
})
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
uj5u.com熱心網友回復:
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
rangeInput.addEventListener("input", () => {
valueInp.textContent = rangeInput.value;
});
valueInp.textContent = rangeInput.value;
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>```
uj5u.com熱心網友回復:
嘗試這個 :
<input type="range" min="1" max="100" value="1" step="1" class="range"/>
<p class="value"></p>
const rangeInput = document.querySelector(".range");
const valueInp = document.querySelector(".value");
range.addEventListener("change",()=>{
valueInp.innerHTML = rangeInput.value;
})
valueInp.innerHTML = rangeInput.value;
每當輸入標簽內的值發生變化時,這里的 addEventListener 就會被執行。
uj5u.com熱心網友回復:
- 您需要在其上連接一個事件偵聽
<input/>器,然后<p >在事件處理程式中更新。 - 順便說一句, 您只能連接事件處理程式
DOMContentLoaded。 - 您可以收聽兩個主要事件:
- 使用
'input'事件來回應每個值的變化,即使<input>元素具有焦點。 - 使用
'change'事件僅在用戶停止與輸入互動時回應更改。
- 使用
- 順便說一句,您應該使用
<output>元素而不是<p>顯示“輸出”值。 - 您應該使用
id選擇特定元素而不是.className選擇器,因為它不是唯一的。 - 切勿
innerHTML用于顯示文本,因為它會使您面臨 XSS 攻擊。- 改為使用
textContent。
- 改為使用
像這樣:
window.addEventListener( 'DOMContentLoaded', onDomLoaded );
function onDomLoaded() {
const rangeInput = document.getElementById('myRangeInput');
const output = document.getElementById('myOutput');
// Show initial value immediately:
output.textContent = rangeInput.value;
// 'input' is the name of the event-type, not the <input> element name.
// you can also use 'change' instead.
rangeInput.addEventListener( 'input', e => {
output.textContent = rangeInput.value;
} );
}
<input id="myRangeInput" type="range" min="1" max="100" value="1" step="1" class="range"/>
<output id="myOutput" for="myRangeInput"></output>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/441529.html
標籤:javascript html
上一篇:定期更新span中的值
