How to set onclick with javascript?

前端 未结 4 592
萌比男神i
萌比男神i 2021-02-05 07:20

I am trying to set the onclick event using javascript. The following code works:

var link = document.createElement(\'a\');
link.setAttribute(\'href\', \"#\");
l         


        
4条回答
  •  再見小時候
    2021-02-05 07:50

    You can add a DOM even listener with addEventListener(...), as David said. I've included attachEvent for compatibility with IE.

    var link = document.createElement('a');
    link.setAttribute('href', "#");
    if(link.addEventListener){
       link.addEventListener('click', function(){
          alert('clicked');
       });
    }else if(link.attachEvent){
       link.attachEvent('onclick', function(){
          alert('clicked');
       });
    }
    

提交回复
热议问题