javascript – 如何将’toggle’事件绑定到元素

有没有办法可以为’toggle’事件处理程序使用’bind’语法?

从文档我可以理解,正确的方法是

$('.selector').toggle( function() {},function() {} );

我的问题是我出于某种原因删除了该元素,然后再将其添加到DOM中.再次添加时,切换不起作用.

因此,我认为应该有一种方法来“绑定”切换.

请帮忙.

这是我正在遵循的文档:
http://jqapi.com/#p=toggle

解决方法

您必须使用 .live().delegate()向所有现在和将来的元素添加处理程序.

问题是.toggle()绑定了点击,在复杂的情况下,比如使用.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个切换函数 – 但是你必须使用开关而不是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

相关文章

kindeditor4.x代码高亮功能默认使用的是prettify插件,prett...
这一篇我将介绍如何让kindeditor4.x整合SyntaxHighlighter代...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面
如何用js控制图片放大缩小