function ValueLimit(min, max, mode){
var v;
if(mode === "h"){
v = document.getElementById("weight_imp").value;
if(v < min){document.getElementById("weight_imp").value = min;}
if(v > max){document.getElementById("weight_imp").value = max;}
}
if(mode === "w"){
v = document.getElementById("weight_imp").value;
if(v < min){document.getElementById("weight_imp").value = min;}
if(v > max){document.getElementById("weight_imp").value = max;}
}
}
我需要用输入元素的 ID 替换模式 这反过来会使代码明显更小 我似乎找不到办法通过它 它应该能够定位页面上的任何元素
最佳答案
我建议您向函数传递一个实际元素而不是选择器(这具有不需要每个 input
都有一个 id
的额外好处)。您还可以使用 Math.min
和 Math.max
来缩短实现时间。
function clampValue (e, min, max){
e.value = Math.min(max, Math.max(min, +e.value))
}
var input = document.getElementById('weight_imp')
function exampleUsage () {
clampValue(input, 0, 100)
}
<input type="number" id="weight_imp">
<button onclick="exampleUsage()">Clamp [0, 100]</button>
关于javascript - 如何将元素 ID 传递给函数的参数? HTML/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376339/