2017-04-12 181 views
0
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來替換模式這應該反過來使代碼顯著小 我似乎無法找到一種方法,通過 通過它應該能夠針對任何頁面上的元素如何將元素ID傳遞給函數的參數? HTML/JS

+4

我不明白你問。你能更具體嗎? –

回答

2

我建議你通過功能的實際元素,而不是一個選擇器(其具有不要求每一位input有一個id額外的好處)。您也可以使用Math.minMath.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>

相關問題