How to change onClick handler dynamically?

前端 未结 11 1562
清歌不尽
清歌不尽 2020-12-02 15:37

I\'m sure there are a million posts about this out there, but surprisingly I\'m having trouble finding something.

I have a simple script where I want to set the onC

11条回答
  •  一向
    一向 (楼主)
    2020-12-02 15:50

    Nobody addressed the actual problem which was happening, to explain why the alert was issued.

    This code: document.getElementById("foo").click = new function() { alert('foo'); }; assigns the click property of the #foo element to an empty object. The anonymous function in here is meant to initialize the object. I like to think of this type of function as a constructor. You put the alert in there, so it gets called because the function gets called immediately.

    See this question.

提交回复
热议问题