简体   繁体   English

如何将元素ID传递给函数的参数? HTML / JS

[英]How to pass an element ID into parameters of a function? HTML/JS

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;}
        }
    }

I need to replace mode with an ID of an input element This should in turn make the code significantly smaller I cannot seem to find a way to pass it through It should be able to target any element on the page 我需要用输入元素的ID替换模式,这反过来又应该使代码明显变小,我似乎找不到找到通过它的方法。它应该能够定位页面上的任何元素

I would suggest that you pass your function an actual element instead of a selector (which has the added benefit of not requiring every input to have an id ). 我建议您为函数传递一个实际元素而不是选择器(选择器具有另一个好处,即不需要每个input都具有id )。 You can also make the implementation much shorter using Math.min and Math.max . 您还可以使用Math.minMath.maxMath.min实现。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM