jQuery 中使用 bind() 和each() 分配事件处理程序的区别?
有人可以告诉我使用bind()分配事件处理程序有什么区别:
$(function () {
$('someElement')
.bind('mouseover', function (e) {
$(this).css({
//change color
});
})
.bind('mouseout', function (e) {
$(this).css({
//return to previous state
});
})
.bind('click', function (e) {
$(this).css({
//do smth.
});
})
});
使用each()来完成同一任务:
$('someElement').each(function () {
$(this).mouseover(function () {
$(this).css({/*change color*/ })
.mouseout(function () {
$(this).css({/*return to previous state*/ });
});
});
});
can someone tell me what the difference between assigning event handlers using bind():
$(function () {
$('someElement')
.bind('mouseover', function (e) {
$(this).css({
//change color
});
})
.bind('mouseout', function (e) {
$(this).css({
//return to previous state
});
})
.bind('click', function (e) {
$(this).css({
//do smth.
});
})
});
using each() for the same task:
$('someElement').each(function () {
$(this).mouseover(function () {
$(this).css({/*change color*/ })
.mouseout(function () {
$(this).css({/*return to previous state*/ });
});
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从您给出的示例中,我认为您实际上是在问使用“绑定”方法和“事件”方法之间有什么区别(如果有的话)。
例如,以下之间有什么区别:
... 和这个?
答案是,这真的不重要。 这是一个偏好问题。 事件方法在语法上更简单,并且涉及更少的输入,但是,据我所知,实际上没有任何区别。 我更喜欢使用绑定方法,因为如果您需要将多个事件附加到同一操作,则可以使用速记事件绑定。 它还可以让您更轻松地了解何时/是否需要“解除绑定”事件。
请参阅此处:.bind 和其他事件之间的差异
但是,从什么实际的问题是,“‘each’方法和‘bind’方法有什么区别”……好吧,这是一个完全不同的野兽。
您永远不应该真正使用“each”方法来附加事件,因为“bind”和“event”方法使用更快的CSS选择器引擎(在jQuery的情况下,它使用Sizzle引擎)。
几乎没有(或从来没有)这样的情况:
...比这样更好:
From the examples you gave, I think you're actually asking what the difference, if any, is there between using the 'bind' method and then 'event' methods.
For example, what's the difference between:
... and this?
The answer is that it really doesn't matter. It's a matter of preference. The event methods are syntactically simpler and involve less typing, but, as far as I know there really isn't any difference. I prefer to use the bind methods because you can use shorthand event binding if you need to attach more than one event to the same action. It also makes it simpler to understand when/if you need to 'unbind' an event.
See here: Difference between .bind and other events
But, from what the actual question asks, "What's the difference between the 'each' method and the 'bind' method"... well, that's a totally different beast.
You should never really use the 'each' method to attach events because the 'bind' and 'event' methods use the much quicker CSS selector engine (in jQuery's case, it uses the Sizzle engine).
There's hardly ever (or never) a case where this:
... is better than this: