2017-08-30 20 views
0

我現在有一個事件監聽器,當輸入改變像這樣的火災:的JavaScript的addEventListener 2個不同的輸入

input = document.getElementById("inputfield1"); 
 

 
input.addEventListener("change", function(e) { 
 
    console.log("Do Something with inputfield1"); 
 
});
<input id="inputfield1">

我現在也想添加第二個輸入,以便將事件如果inputfield2也發生變化,則被解僱。
我可以使用OR聲明添加它嗎?還是應該爲第二個字段創建一個全新的事件偵聽器?

+0

所以另一個事件綁定到另一個元素..... – epascarello

+1

只要定義爲事件偵聽器命名功能,並使用相同的一個你喜歡的任何元素。 – Redu

+0

或者你可以谷歌你的問題的標題! – undefined

回答

0

您必須明確附加每個元素的事件處理程序。下面有一個片段,它顯示了你如何做到這一點。

document.querySelectorAll('.jsInputField') 
 
     .forEach(function(element){ 
 
       element.addEventListener('change', function(event){ 
 
        var elementId = event.currentTarget.getAttribute('id') 
 
        console.log("Do Something with " + elementId); 
 
       }); 
 
     });
<input id="inputfield1" class="jsInputField"> 
 
<input id="inputfield2" class="jsInputField">

更新

正如拉姆指出在他的評論,NodeList.prototype.forEach,是從最新的瀏覽器都支持(如鉻51等)的NodeList的方法。欲瞭解更多信息,請看看here

爲了避免在上面的鏈接中使用上面提到的polyfill來處理不支持此方法的情況,可以使用簡單的for語句。

+0

值得一提的是'NodeList.prototype.forEach'是一種不被廣泛支持的新方法! – undefined

+0

@Ram謝謝你的評論!我會更新我的帖子。 – Christos

+0

@Ram我同意,但它可能沒有做任何比'Array.from(nodeList).forEach()' – Redu

1

function f(element) { console.log(element.id, element.value); }
<input id="inputfield1" onchange="f(this)"> 
 
<input id="inputfield2" onchange="f(this)">

function f(event) { 
 
    var element = event.currentTarget 
 
    console.log(element.id, element.value) 
 
} 
 

 
document.getElementById("inputfield1").addEventListener("change", f) 
 
document.getElementById("inputfield2").addEventListener("change", f)
<input id="inputfield1"> 
 
<input id="inputfield2">

0

使用querySelectAll()和用於循環

function myFunction(){ 
 
    input =document.querySelectorAll("#inputfield1 , #inputfield2"); 
 
    var i; 
 
    for (i = 0; i <input.length; i++) { 
 
    input[i].addEventListener("keypress", function() { 
 
     alert("hi from"+this.id); 
 
    }); 
 
    } 
 
    } 
 
    myFunction();
<input id="inputfield1"> 
 
    <input id="inputfield2">

相關問題