如何将事件侦听器添加到多个元素ID

时间:2016-10-19 14:25:45

标签: javascript

以下是我将侦听器添加到多个ID的方法。

function onImageClick(event) {
//i am not getting below console msg
  console.log('Event Registered');
}

var queryResult = document.getElementsByClassName('ui-grid-cell');
Array.from(queryResult).forEach(function(element) {
  document.getElementById(element.id).addEventListener("click",onImageClick);
});

以上方法对我不起作用。我在做什么错误?

4 个答案:

答案 0 :(得分:1)

这将有效



 function onImageClick(event) {
          alert('Event Registered');
        }
        
        var queryResult = document.getElementsByClassName('ui-grid-cell');
        
        for(var i=0;i<queryResult.length;i++){
        if(queryResult[i].id && queryResult[i].id !=""){
            document.getElementById(queryResult[i].id).addEventListener("click",onImageClick);
        }
        }
&#13;
img{
margin:15px;
padding:10px;
border-radius:10px;
box-shadow:1px 1px 1px #ccc;
}
&#13;
<img title='this should listen' src='https://www.google.com.eg/images/nav_logo242.png' class='ui-grid-cell' id='div1'/>
<img src='https://www.google.com.eg/images/nav_logo242.png' class='ui-grid-cell'/>
<img title='this should listen' src='https://www.google.com.eg/images/nav_logo242.png' class='ui-grid-cell' id='div2'/>
<img src='https://www.google.com.eg/images/nav_logo242.png' class='ui-grid-cell'/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的相同代码工作正常,也许您错过了将ID设置为图像?

&#13;
&#13;
function onImageClick(event) {
//i am not getting below console msg
  console.log('Event Registered');
}

var queryResult = document.getElementsByClassName('ui-grid-cell');
Array.from(queryResult).forEach(function(element) {
  document.getElementById(element.id).addEventListener("click",onImageClick);
});
&#13;
<img src="https://dummyimage.com/50x50/000/fff"
     class="ui-grid-cell" id="one">
<img src="https://dummyimage.com/50x50/ccc/fff"
class="ui-grid-cell" id="two">
<img src="https://dummyimage.com/50x50/123456/fff"
class="ui-grid-cell" id="three">
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这种方法应该有效:

var queryResult = document.getElementsByClassName('ui-grid-cell');
Array.from(queryResult).forEach(function(element) {
    element.addEventListener("click",onImageClick);
});

答案 3 :(得分:-2)

如果您使用JQuery,请使用此

$(".ui-grid-cell").click(function(){

});