Jquery . click or Function

Asked

Viewed 351 times

-1

As I get used to it more and more

<input type=button onclick="TESTE()">

<script>
function TESTE(){
...
}

To use the jquery method

<input type=button id="teste">
<script>
$("#teste").click(function() {
...
}

I know jQuery is a more modern method, but is it better? or can I still make a salad between the two methods?

NOTE: I ask this because I recently read an article where a person made a comparison with XML and JSON and in certain cases JS was faster working directly with XML. So sometimes we do it just because it’s modern!

2 answers

3


Advantage in putting direct code in the element

One of the difficulties I have with jQuery is in maintaining code that I didn’t make.

The problem is in identifying where are in javascript, the code of the handlers associated via jQuery, so that connecting the tips after the code is already ready can show an extremely tiring task.

This problem is avoided by putting the code directly into the element, even if it is to call a method, which will do everything else... actually this is the way I would recommend, in order to separate the rest of the script into an external file, that can take advantage of the browser cache.

Advantage of using jQuery to associate events

In terms of organization, using event association via jQuery is best, as it allows HTML (presentation) to be separated from functionality (behavior). Thus the presentation is uncoupled from demeanor.

Using jQuery is also more practical, and therefore more productive on several occasions.

  • With it it is possible to assign several handlers to the same event, which is not possible by placing the code directly in the element, at least not in an easy way.

  • With it it is possible to associate events to multiple elements at the same time, using class selectors, for example.

The total separation in an external script file has another advantage, which for me is the main: js file cache... but this is not an advantage of jQuery, since in the other alternative, this is also possible.

Which of the alternatives is better

Like almost everything where there are several alternatives to choose from: use common sense. It will depend on the goal. Just align the goal with these advantages and disadvantages, plus others you identify.

Personally I find it plausible to use both options, provided that with common sense.

  • @Downvoter: could explain what is wrong with this answer?

0

It’s always best you leave the JavaScript unlinked separate from the HTML, as well as CSS. Regarding functionality, the result will be the same, it is more a matter of organization and practicality.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.