![](/img/trans.png)
[英]Multiple charts with event listeners - how to find which chart has fired the listener? Test case and screenshot are attached
[英]How to find out which event listener has fired
我有一堆輸入字段,其中使用for循環和類名稱附加事件偵聽器。 有沒有辦法可以獲取觸發的輸入字段的ID? 我有大約40個輸入字段,我想從觸發的輸入中獲取id並將其作為變量傳遞給函數。
HTML -
<input type="text" id="t11Text1" class="text1 input">
<input type="text2" id="t11Text2" class="text2 input">
<input type="text" id="t12Text1" class="text1 input">
<input type="text2" id="t12Text2" class="text2 input">
JS -
var onChange = document.querySelectorAll('.input');
var onChangeSelect = document.querySelectorAll('.select');
for (var i = 0; i < onChange.length; i++) {
onChange[i].addEventListener("input", function() {
myFunction();
});
}
您可以在匿名函數中訪問event
對象 , event.target.id
將是元素的id
。
var onChange = document.querySelectorAll('.input');
var onChangeSelect = document.querySelectorAll('.select');
for (var i=0; i < onChange.length; i++){
onChange[i].addEventListener("input", function (event) {
// event.target.id
myFunction();
});
}
雖然@Josh Crozier的回答是正確的,並且恰好回答了這個問題,但我會避免設置這么多聽眾並做這樣的事情:
HTML:
<form class="myformclass">
<input type="text" id="t11Text1" class="text1 input">
<input type="text2" id="t11Text2" class="text2 input">
<input type="text" id="t12Text1" class="text1 input">
<input type="text2" id="t12Text2" class="text2 input">
<select class="input">
<option value="0">0</option>
<option value="1">1</option>
</select>
</form>
JS:
var myForm = document.querySelector('.myformclass');
myForm.addEventListener("input", function getInput(e) {
var input = e.target;
if (input.classList.contains("input")) {
doWhateverWithTheInput(input);
}
});
function doWhateverWithTheInput(elt) {
console.log(elt);
}
在事件偵聽器回調函數中,您將on event.target
接收一個事件對象,該事件對象使用觸發事件的元素填充
看下面的例子:
var inputs = document.querySelectorAll('[id*=input]'); // in this case works also with `document.getElementsByTagName('input')` var selects = document.querySelectorAll('[id*=select]'); // the definition of the event listener var inputEventListener = function(event) { console.log(event.target.id); //event.target.style.background = '#FDFDFD'; //event.target - is the actual element; } for (var i = 0, length = inputs.length; i < length; i++) { // here is added the event listener for the input elements inputs[i].addEventListener('input', inputEventListener); } for (var i = 0, length = selects.length; i < length; i++) { // here is added the event listener for the select elements selects[i].addEventListener('change', inputEventListener); }
<!-- Ignore this, I'm too lazy to write 100 inputs --> <!-- Adding 100 inputs to the page so we can run some test on them --> <script> for (var i = 0; i < 100; i++) { document.write('<label for="input' + i + '">Input ' + i + '</label> <input id="input' + i + '"/><select id="select' + i + '"><option>1</option><option>2</option><option>3</option></select><br />'); } </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.