简体   繁体   中英

Event handling in javascript

I've learned that you can declare event handlers within either the HTML or the Javascript. My question is, is it better to do so in the Javascript or the HTML? Does it make a difference? If so, why?

Almost always JavaScript. It's cleaner, easier to maintain and separates the HTML from the JavaScript.

For example, you could write this:

<button onclick="do_something(this)">Button 1</button>
<button onclick="do_something(this)">Button 2</button>
<button onclick="do_something(this)">Button 3</button>
<button onclick="do_something(this)">Button 4</button>

Or you could leave the HTML as just HTML and bind the event handler from within your script:

$('button').click(function() {
    // Do something
});

It very much depends on your requirements. Adding an inline listener is no more difficult than adding a class or id, so whether you add them at the server (ie inline) or client (dynamically) depends on what suits a particular case. Having them in–line makes it clear to anyone maintaining the code where the listeners are just by looking at the server code or generated HTMl. Otherwise, they must search through script files to find out where they are.

Just use whatever is mote efficient for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM