如何绑定“切换”按钮事件到元素
有没有办法可以将“绑定”语法用于“切换”事件处理程序?
从文档中我可以理解正确的方法是
$('.selector').toggle( function() {}, function() {} );
我的问题是我出于某种原因删除该元素,然后再次将其添加到 DOM 中。再次添加时,切换不起作用。
因此,我认为应该有一种方法来“绑定”切换。
请帮忙。
这是我正在关注的文档: http://jqapi.com/#p=toggle
Is there a way I can use the 'bind' syntax for the 'toggle' event handler ?
From the docs I can understand that the correct way is
$('.selector').toggle( function() {}, function() {} );
My problem is that I am removing that element for some reason, and then again add it to the DOM. On adding it again, the toggle does not work.
Thus, I think there should be a way to 'bind' the toggle.
Help please.
This is documentation I am following:
http://jqapi.com/#p=toggle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的问题是,由于某种原因我删除了该元素,然后再次将其添加到 DOM 中。再次添加它时,切换不起作用。
我认为,这取决于您删除元素的具体方式。如果您使用 remove 函数,所有事件和 jquery 数据也将从元素中删除。它与 detach 函数相反,非常适合删除您计划稍后插入回文档中的元素。
My problem is that I am removing that element for some reason, and then again add it to the DOM. On adding it again, the toggle does not work.
I think, it depends on how exactly you remove element. If you use remove function, all events and jquery data will be removed from element too. And it's opposite with detach function, making it ideal for removing elements you plan to insert back in the document later.
参考 : .bind , .trigger
尝试示例:http://jsbin.com/ixapo4/2
Refer : .bind , .trigger
Try the Example : http://jsbin.com/ixapo4/2
尝试使用 live 功能。这是文档。 链接文本
希望对您有所帮助。
Try to use live function. Here is documentation. link text
Hope it will help you.
您必须使用
.live()
或.delegate()
添加处理程序所有现在和未来的元素。问题是
.toggle()
绑定点击,在复杂的情况下,例如使用.live()
或.delegate()
< /strong>你必须自己做。来自 jQuery 文档:滚动你自己的切换(这可以使用 mod N 而不是 mod 2 轻松扩展到 N 个切换函数 - 但随后你必须使用 switch 而不是 JS 条件运算符):
如果你想包含 2 个函数,那么它们必须是自我执行。这对于传递参数很有好处...因此形式为:
一个简单的例子(不使用参数):
在 jsFiddle 上尝试一下
一个更复杂的示例(使用参数):
在 jsFiddle 上尝试一下
You must use either
.live()
or.delegate()
to add handlers to all now and future elements.The problem is that
.toggle()
binds click, and in complicated cases, like using.live()
or.delegate()
you have to make your own. From the jQuery Docs:Roll your own toggle (this can be easily extended to N toggled functions using mod N instead of mod 2 - but then you have to use a switch instead of the JS conditional operator):
If you want to include 2 functions, then they must be self executing. This would be good for passing arguments in... so the form would be:
A simple example (no arguments used):
try it out on jsFiddle
A more complex example (arguments used):
try it out on jsFiddle