onclick=“” vs event handler

前端 未结 8 2206
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 00:20

If I want a function to be executed, I prefer doing inline js:

Click me

becaus

8条回答
  •  时光取名叫无心
    2020-11-22 00:58

    Despite what other people may think, I think there are redeeming value to inlining listeners in markup. Specifically, it gives you a lot more freedom to modifying the DOM nodes. If you're adding listeners though JavaScript, the listeners are lost when you replace the innerHTML of any parent nodes. If you're inlining the listeners in markup, you can clone the node, make modifications to it, then replace the original node with the node you just cloned and modified.

    Perhaps it's better to describe it in a specific use case. I want to make changes to multiple part of the document without triggering reflow multiple times. So in this case, I can clone the node, make any change to it (no reflow since its detached), then replace the previous node with the modified one (triggering one reflow). With inlined listeners, this prevents any listeners from getting lost during the replacement.

提交回复
热议问题