Why are more people currently using a script to assign event handlers and assign events from an html element?

As a student, I like to look at a lot of source texts. Since I started learning JavaScript about a year ago, I notice a tendency for people who don’t use traditional event handlers like in onclick="doSomething()", but are increasingly using methods such asdocument.getElementById("someId").onclick = function(){..some code..};

What is the reason for this trend?

+3
source share
5 answers

Assigning handlers in Javascript puts all the code in one place instead of scattering it throughout the HTML.
This helps separate content from a script, just as CSS helps separate content from style.

, Javascript .

Javascript.

+14

, :

() onclick JavaScript:

document.getElemenbyId("someId").onclick = function(){..some code..};

..., , : . DOM2 (addEventListener attachEvent IE [IE9 addEventListener finally]):

document.getElementById("someId").addEventListener("click", function() { ... }, false);
// or
document.getElementById("someId").attachEvent("onclick", function() { ... });

... — . onclick, .

" " - . , , .

+5

HTML , .

CSS.

JavaScript-, .

- , , , script , HTML.:)

+2

I think most people use jQuery. $("#someId").click(function(){})and when you want to attach an event to many elements, jQuery simplifies and puts your function in one place.

0
source

As mentioned in other answers, the main reason is the separation of problems (in this case, keeping the behavior separate from the content), which is perfectly reasonable. However, this is not always the only consideration. I previously wrote a long answer to the corresponding question .

0
source

Source: https://habr.com/ru/post/1777344/


All Articles