[英]javascript - addEventListener with an array of input
我需要使用addEventListener
來自動更新鍵入到不同input text
(實際上是4個input
標簽)中的值
這是HTML代碼:
<td class="col-md-4">
<label for="lab1"><b>$\mathbf{M_{1}}$</b></label>
<input type="text" class="form-control input-sm" id="lab1" />
</td>
<td class="col-md-4">
<label for="lab2"><b>$\mathbf{M_{2}}$</b></label>
<input type="text" class="form-control input-sm" id="lab2" />
</td>
<td class="col-md-4">
<label for="lab3"><b>$\mathbf{M_{3}}$</b></label>
<input type="text" class="form-control input-sm" id="lab3" />
</td>
</tr>
<tr>
<td class="col-md-4">
<label for="lab4"><b>$\mathbf{\Theta_{1}}$</b></label>
<input type="text" class="form-control input-sm" id="lab4" />
</td>
我想在修改值時更新它們,而不必在input
外部單擊。
我試圖在main
使用以下addModifyEvent
函數:
function addModifyEvent() {
var inputList = document.querySelectorAll('input.form-control');
for (var i=0; i<inputList.length; i++)
{
inputList[i].addEventListener('input', function()
{
console.log(inputList[i].value); });
}
}
但這不起作用(我收到TypeError: inputList[i] is undefined
)。
我不知道我是否應該做得更好:
inputList[i].addEventListener('inputList['+i+']',
或封閉的東西
inputList[i].addEventListener('input',
我想為每個input tag
添加一個事件eventlistener
input tag
。
有人可以告訴我正確的語法嗎?
謝謝
事件處理程序的上下文是觸發事件的輸入元素。 更換inputList[i]
與this
:
console.log(this.value);
使用this.value
的代碼的略微修改版本可以正常工作:
function addModifyEvent() {
var inputList = document.querySelectorAll('input.form-control');
for (var i = 0; i < inputList.length; i++) {
inputList[i].addEventListener('input', function () {
console.log(this.value);
});
}
}
演示: http : //jsfiddle.net/jfriend00/9ny3wcxu/
您不能在事件處理程序中引用inputList[i]
,因為在調用事件處理程序時(有時稍后), for
循環已經完成運行,因此i
指向了inputList
HTMLCollection對象的末尾。
您可以通過僅使用this
作為導致事件的對象的指針來解決問題,因此this.value
是剛剛被修改的input
字段的值。
事件觸發時,
console.log(inputList[i].value);
inputList[i]
無效,因為它是用於綁定事件偵聽器的for
循環的一部分。
使用this
來獲取觸發事件的當前元素,
console.log(this.value);
完整代碼
function addModifyEvent() {
var inputList = document.querySelectorAll('input.form-control');
for (var i = 0; i < inputList.length; i++) {
inputList[i].addEventListener('input', function () {
console.log(this.value);
});
}
}
您可以使用閉包(如果不熟悉,請搜索並閱讀一下)。 代碼如下:
for (var i=0; i<inputList.length;i++)
{
(function(i){
inputList[i].addEventListener('input',function(){
console.log(inputList[i].value); });
}
})(i);
}
基本上, i的值在函數內保持不變。 每當您在異步循環中執行某些操作時,這都是必需的。
好處是您不需要更改訪問值的方式,只需要將它們包含在閉包函數中即可。
希望這可以解決您的問題,而無需更改訪問數組的方式。
如您在示例中看到的,我打印了2個控制台,一個用於您的輸入 ,另一個用於您的i。
所以你的問題是:
在偵聽器函數中,當您嘗試訪問console.log(inputList [i] .value); 因此,那時您的i為4,而您的輸入數組長度為0-3 ,由於for循環,我將增加至4,因此您不確定,因為數組中不存在inputList [4] 。
工作示例 : http : //jsfiddle.net/kevalbhatt18/gqce9htx/
調試錯誤示例: http : //jsfiddle.net/kevalbhatt18/gqce9htx/2/
var inputElem = document.getElementsByTagName('input');
for(var i = 0; i < inputElem.length; i++) {
inputElem[i].addEventListener('click', function(){
alert(this.value);
}, false);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.