How to set onclick with javascript?

前端 未结 4 594
萌比男神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:28

    Setting an attribute doesn't look right. The simplest way is just this:

    link.onclick = function() {
        alert('click');
    };
    

    But using addEventListener as JCOC611 suggested is more flexible, as it allows you to bind multiple event handlers to the same element. Keep in mind you might need a fallback to attachEvent for compatibility with older Internet Explorer versions.

提交回复
热议问题