[英]Can onchange be triggered within HTML for DIV by passing function(this.value);
[英]Is there a way to access this.value (of an input) from within a function call in HTML
我有一个 HTML 输入,我想在手动输入时将其限制为 100,我有一个最小值和一个最大值,因此如果他们使用微调器(向上和向下箭头)它已经限制了它。 为此,我想调用一个 function,而不是使用内联 Javascript,它可用于整个 HTML 文件中的多个功能。
想要的功能:
<input id="..." oninput="foo()">
...
<script>
function foo() {
if(this.value > 100) {
this.value = 100; // If the inputted value is 99, do nothing, if it's 999, change it to 100
}
}
</script>
我想要一个这样的功能,它可以让我这个 this.value - 但是 - this.value 无法从 foo function 中访问(我认为???)。
所以我试着这样做:
<input id="..." oninput="foo(this.value)">
...
<script>
function foo(value) {
if(value > 100) {
value = 100;
}
}
</script>
但我认为只有值的“副本”更改为 100,而不是实际值。 所以我可以通过返回这样的值来做到这一点:
<input id="..." oninput="this.value = foo(this.value)">
...
<script>
function foo(value) {
if(value > 100) {
value = 100;
}
return value;
}
</script>
但是这段代码看起来很笨拙,有没有更好的方法来做到这一点?
编辑:已解决,谢谢大家的回答,这是我现在的代码。 我还解析输入以确保它只是数字。 没有“e”或“.” 因为我只关心整数。
<input id="area-level-input" type="number" value="1" min="1" max="100" oninput="limitInput.call(this, 100)" onkeydown="isValidNumberEntry()">
其中各自的功能是:
function limitInput(limit) {
if(this.value > limit) {
this.value = limit;
}
}
function isValidNumberEntry() {
// keyCode 8: Backspace; keyCode 46: Delete
return (event.keyCode === 8 || event.keyCode === 46) ? true : !isNaN(Number(event.key));
}
您可以使用call
方法:
<input id="..." oninput="foo.call(this)">
...
<script>
function foo() {
if(this.value > 100) {
this.value = 100; // If the inputted value is 99, do nothing, if it's 999, change it to 100
}
}
</script>
你有两种方法来完成你正在尝试的事情:
两者都有相同的结果,并且 function 如您所料:
<input oninput="foo(this)"/>
或者
<input oninput="foo(event)"/>
那么你的 function 可以是:
function foo(thisChoice) {
if(thisChoice.value > 100) {
thisChoice.value = 100;
}
}
或者
function foo(eventChoice) {
if(eventChoice.target.value > 100) {
eventChoice.target.value = 100;
}
}
请记住,一个您只传递输入标签,另一个您将整个事件传递给 function。
你的方法是正确的。
您可以直接在 function 中修改元素的值,使其更具可读性和可重用性。 例如:
<input type="number" min="0" max="100" oninput="limitTo(100, this)" />
<script>
function limitTo(upperLimit, el) {
if (el.value > upperLimit) {
el.value = upperLimit;
}
}
</script>
我还建议将 input 元素的type
属性设置为number
。 优点是浏览器将确保只接受数字,并且允许设置属性max 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.