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

标签 javascript html

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.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>

关于javascript - 如何将元素 ID 传递给函数的参数? HTML/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43376339/

相关文章:

javascript - 在网站中实现预加载器

javascript - 使用“添加用户”按钮添加 HTML 字段

javascript - 在 POST 变量中使用 ‘&’

Javascript:提交文本区域的更改不起作用

html - 尽管其中一部分已经有另一个链接,如何在整个图片上激活一个链接?

java - 在 servlet 中包含 html 模板

javascript - jquery 对话框中的 html5 视频 - 第一次点击时 JavaScript 不会播放

javascript - 在 PHP 中运行 SQL 查询时自动刷新结果 div

javascript - 在 three.js 中编程一个洞/空白空间

html - 为什么 Firefox 即使输入名称不同也会自动完成?