有没有一种方法可以将“绑定(bind)”语法用于“切换”事件处理程序?
从文档我可以理解正确的方法是
$('.selector').toggle( function() {}, function() {} );
我的问题是我出于某种原因要删除该元素,然后再次将其添加到 DOM。再次添加时,切换不起作用。
因此,我认为应该有一种方法来“绑定(bind)”切换。
请帮忙。
这是我正在关注的文档: http://jqapi.com/#p=toggle
最佳答案
您必须使用 .live()
或 .delegate()
将处理程序添加到所有现在的和 future 的元素。
问题是 .toggle()
绑定(bind)点击,在复杂的情况下,比如使用 .live()
或 .delegate()
你必须自己制作。来自 jQuery 文档:
The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting.
滚动你自己的切换(这可以使用 mod N 而不是 mod 2 轻松扩展到 N 切换功能 - 但你必须使用 switch 而不是 JS 条件运算符):
var counter = 1;
$('.selector').live("click", function() {
counter++ % 2 ?
// First set of actions :
// Second set of actions;
});
如果你想包含 2 个函数,那么它们必须是自执行的。这对于在...中传递参数很有用,因此形式为:
var counter = 1;
$('.selector').live("click", function() {
counter++ % 2 ?
(function() { ... }()) : // <== First function
(function() { ... }()); // <== Second function
});
一个简单的例子(没有使用参数):
(function() {
var counter = 1;
$('.selector').live("click", function() {
counter++ % 2 ?
$("div").html("First one!") :
$("div").html("Numero dos!");
});
$(function() {
$("body").prepend('<input type="button" ' +
'class="selector" value=" Click Me! " />');
});
}());
try it out on jsFiddle
一个更复杂的例子(使用了参数):
(function() {
var counter = 1;
$('.selector').live("click", function() {
// Note that the self executing functions are only
// necessary if you want to use arguments.
counter++ % 2 ?
(function() {
$("div").html("First one! Num: " + ($(event.target).index() + 1))
}(event)) :
(function() {
$("div").html("Numero dos! Num: " + ($(event.target).index()+1))
}(event));
});
$(function() {
$elie = $('<input type="button" class="selector" value="Click Me!" />');
$elie.clone().prependTo("body");
$elie.clone().prependTo("body");
$elie.clone().prependTo("body");
});
}());
try it out on jsFiddle
关于javascript - 如何将 'toggle' 事件绑定(bind)到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3854678/