Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

onchange - What is best way to perform jQuery .change()

I have 2 separate scripts that essentially do the same thing. I built them over time and just discovered I am using a couple different means to get to the same result.

I want to standardize and use the best practices method in both cases.

One way I test a change event is this:

$('input[name="status"]').change(function() {});

Another way I am testing a change event is this:

$("#email").bind("change", function(e) {});

Which way is best? What is the difference between the 2?

Thanks for helping me understand this.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Before jQuery 1.7, change() was simply a short cut for bind("change").

As of 1.7 however, on() was introduced, and is preferred to bind(). That now means change() is a shortcut for on("change"), and in fact all bind() calls will now call on() internally.

In short, they do the same thing. I find the explicit use of on() (or bind()) preferable, but as long as you're consistent throughout your code base, I don't see any real differences.

One could argue that using change() over on("change") is "better", as a typo in the word "change" would throw a parse error in the first instance ("undefined is not a function"), but would fail silently with on()... but obviously your unit tests would catch that, right? ;).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...