如何在具有特定类的所有dom元素上添加EventListener?

时间:2018-05-09 13:28:00

标签: javascript jquery typescript onclick addeventlistener

我的DOM中有一些具有class =“foo”的跨度,所有跨度都是动态创建的。

使用TypeScript我想在创建后为所有人添加onClick事件。

我有这样的事情:

[HTML]
<ej-treegrid id="TreeGridContainer" [dataSource]="treeGridData" 
(create)="create($event)" (collapsed)="collapsed($event)" (expanded)="expanded($event)" (rowSelected)="rowSelected($event)" (actionComplete)="actionComplete($event)"
//..
</ej-treegrid>

[TS]
  create(args) {
        /To update the height of TreeGrid during load time
         this.updateTreeHeight();
    }

    collapsed(args) {
       //To update the height of TreeGrid during collapse action
        this.updateTreeHeight();
    }

    expanded(args) {
       //To update the height of TreeGrid during expand action
       this.updateTreeHeight();
    }

    rowSelected(args) {
        //To update the height of TreeGrid while adding any row
         this.updateTreeHeight();
    }

    actionComplete(args) {
      //To update the height of TreeGrid while saving the newly added row and deleting the existing row
       if (args.requestType == "addNewRow" || args.requestType == "delete") {
            this.updateTreeHeight();
        }
    }
    updateTreeHeight=function() {
    var tree = $("#TreeGridContainer").ejTreeGrid("instance"),
        toolbar = $("#TreeGridContainer_toolbarItems").height(),
        model = tree.model,
        totalLen = tree.getExpandedRecords(model.updatedRecords);
    if (toolbar == undefined)
        toolbar = 0;
    //To calculate the height of TreeGrid as per records count
    var height = model.rowHeight * totalLen.length + tree.getHeaderContent().height() + toolbar + 4;
    //Update height using setModel
    var sizesettings = { height: height.toString() };
    tree.setModel({ "sizeSettings": sizesettings });
}

但我无法在NodeListOf上执行forEach。

foos = Array.from(foos)不起作用,因为:'from'在类型'ArrayConstructor'上不存在。

3 个答案:

答案 0 :(得分:3)

由于您使用jquery标记了问题,因此jquery方式为:

$(".foo").click( function() { 
   // Do something here
}); 

答案 1 :(得分:2)

为此使用简单的for循环。您可以在foos数组中获取每个索引的元素,并为它们分配click事件。这是因为querySelectorAll返回一个NodeList,它像数组一样被索引,但不是一个数组,所以你不能调用它上面的数组方法,因为它不是一个真正的数组。

var foos = document.body.querySelectorAll(".foo"));
for(var i=0; i<foos.length; i++){
    foos[i].addEventListener("click", () => { 
        console.log(item); 
    });
});

答案 2 :(得分:1)

我制作了三种不同的方法,它们非常简单,请打开每个代码段以查看它是否有效。

1 - 此示例显示如何添加侦听器 AFTER 创建元素。

for (var i = 0; i < 4; i++){
  var a = document.createElement('input');
  a.type = 'button';
  a.value = 'click me ' + i;
  a.className = 'foo';
  document.body.append(a);
}

//JQUERY WAY
$('.foo').on('click', function(){
  console.log(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

2 - 此示例显示如何添加侦听器 BEFORE 创建元素。

//JQUERY WAY
$(document).on('click', '.foo', function(){
  console.log(this.value);
});

for (var i = 0; i < 4; i++){
  var a = document.createElement('input');
  a.type = 'button';
  a.value = 'click me ' + i;
  a.className = 'foo';
  document.body.append(a);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

3 - 最后,如果不想要jQuery,这里有一个 Vanilla JS 示例:

for (var i = 0; i < 4; i++){
  var a = document.createElement('input');
  a.type = 'button';
  a.value = 'click me ' + i;
  a.className = 'foo';
  document.body.append(a);
}

//VANILLA JS WAY
var myElems = document.querySelectorAll('.foo');
myElems.forEach(function(elem){
  elem.onclick = function(){
    console.log(elem.value);
  }
});