如何找出触发了哪个事件监听器

时间:2015-05-26 13:38:46

标签: javascript events

我有一堆输入字段,其中使用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();
    });
}

3 个答案:

答案 0 :(得分:9)

您可以访问匿名函数中的event objectforeach($_POST['chk'] as $key => $value) { ... }将是元素的event.target.id

id

答案 1 :(得分:2)

虽然@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);
}

答案 2 :(得分:1)

在事件侦听器回调函数中,您会收到一个事件对象,该事件对象填充了触发事件的元素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>&nbsp;<input id="input' + i + '"/><select id="select' + i + '"><option>1</option><option>2</option><option>3</option></select><br />');
  }
</script>