How to add a onclick event to an element using javascript

前端 未结 7 1088
忘掉有多难
忘掉有多难 2020-12-04 02:03

I have created an element using document.getElementsByClassname, and would like to add a onclick event to this element, so that when someone clicks on this element onclick f

相关标签:
7条回答
  • 2020-12-04 02:32

    Try this:
    document.getElementsByClassName always returns array of elements.

     var element= document.getElementsByClassName('classname');
     for(var i=0;i<element.length;i++){
          element[i].addEventListener("click", function(){alert('clicked')}, false);   
     }
    
    0 讨论(0)
提交回复
热议问题