什么是执行jQuery .change()的最佳方法 [英] What is best way to perform jQuery .change()
问题描述
我有2个独立的脚本,它们基本上可以完成相同的操作.我逐渐建立了它们,只是发现我正在使用几种不同的方法来获得相同的结果.
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) {});
哪种方法最好? 2和有什么区别?
Which way is best? What is the difference between the 2?
感谢您帮助我理解这一点.
Thanks for helping me understand this.
推荐答案
在jQuery 1.7之前,change()
是的捷径.
Before jQuery 1.7, change()
was simply a short cut for bind("change")
.
但是从1.7开始, on()
引入了,它是bind()
的首选.现在,这意味着change()
是on("change")
的快捷方式,实际上所有bind()
调用现在都将调用 on()
.
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.
简而言之,他们做同样的事情.我发现最好显式使用on()
(或bind()
),但是只要您在整个代码库中保持一致,就不会发现任何真正的区别.
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.
有人可能会说,在on("change")
上使用change()
是更好的",因为单词"change"中的错字会在第一个实例中引发解析错误("undefined not a function"),但会on()
静默失败...但是很显然,您的单元测试会抓住这一点,对吧? ;).
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? ;).
这篇关于什么是执行jQuery .change()的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!