简体   繁体   English

从Javascript事件处理程序引用文档作用域

[英]Referencing the document scope from a Javascript Event Handler

I have a very simple event handler (change) on a form control (input type-number) and I want to do some work based on the value entered. 我在表单控件(输入类型-编号)上有一个非常简单的事件处理程序(更改),我想根据输入的值做一些工作。 This works great with use of the 'this' keyword. 使用'this'关键字非常有效。

I'm running into a scope problem when I try to also check the value of another control (another input type-number). 当我尝试同时检查另一个控件(另一个输入类型-编号)的值时,我遇到了范围问题。 I understand this is a scope issue but I just can't figure out how to reference the second control from the event handler of the first. 我知道这是一个范围问题,但我只是想不通如何从第一个控件的事件处理程序中引用第二个控件。

So for instance; 例如

if (this.value) != "" { do something }

Works great, but; 效果很好,但是;

if (this.value != "" && document.getElementById("someothercontrol").value) != "") { do something else }

Fails. 失败 As I indicated, I realize this document object is out of scope, but I don't know the syntax to reference it (I presume there is a way). 正如我所指出的,我意识到这个文档对象超出了范围,但是我不知道引用它的语法(我想有办法)。

Just save the reference to the input element at a higher scope, here is an example: 只需将对输入元素的引用保存在更高的范围内,这是一个示例:

 const inputs = document.querySelectorAll('input'); const input1 = document.getElementById('input1'); const input2 = document.getElementById('input2'); for (let input of inputs) { input.addEventListener('change', () => { console.log(input1.value); console.log(input2.value); }) } 
 <input id="input1" type="text"> <br> <input id="input2" type="text"> 

If you don't want the variables to be at global scope you can put it in an immediately invoked function expression: 如果您不希望变量位于全局范围内,则可以将其放在立即调用的函数表达式中:

(() => {
   // your scoped code here
})()

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

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