Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - JQuery - Best way of wiring GUI objects to events?

Ever since JQuery came along a few years ago I've been using it in all my client-side scripts. Initially I used the '$() syntax to grab and manipulate objects this, to me, is the 'old skool' paradigm of explicitly wiring up button events to functions:

<button onClick='myFunction(this);' ...  />

with a related function:

function myFunction(obj){
    alert('this is how old-timers like me do it!')
}

Some of my colleagues prefer to do the attaching of scripts to events a la JQuery:

$(document).ready(
    $("#myButton").click(
        function(event){
            alert('this is the newer JQuery way of doing things');
        }
    );
);

Initially I found the overly-bracey JQuery syntax with its reliance on anonymous functions etc. difficult to read, but my eyes and brain have adjusted so I'm happy with either way now. I would however like our codeshop to be consistent. Does anyone have any opinions on which approach is 'better'?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The jQuery version you have can be much smaller as well:

$(function() {
  $("#myButton").click(function(){
    alert('this is the newer JQuery way of doing things');
  });
});

I'd go with this or any other unobtrusive route (not inline handlers), there are just fewer issues overall, and maintenance can be much easier. Remember with this route there can be no JavaScript in your page, it can be loaded and cached once by your client meaning faster page loads as well.

There are many things you just can't do properly (or cross-browser) inline as well, for example the very useful mouseenter and mouseleave (so they don't fire when entering a child) events are only available inline in IE.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...