开发者

Click Toggle (jQuery)

$("li").hover(
function () {
    // do x
},
function () {
    // do y
});

.. thats for hov开发者_C百科er, how would I do the same for click toggle, i.e do x on click and y on second click?

Manythanks


$('li').toggle(function() {
 alert(1)
}, function() {
 alert(2);
});


$.toggle() will take any number of functions. Here it is with two:

$("li").toggle(
  function() { /* do x */ },
  function() { /* do y */ }
);

Demo: http://jsfiddle.net/vbkBQ/


One problem with toggle() is that it automatically calls event.preventDefault(). Here's one way that will let you leave the default action in place or allow you to only call it conditionally.

$("a").click(function(event){
    var toggle = ($(this).data('toggle') == undefined) ? true : $(this).data('toggle');
    console.log(toggle);

    if(toggle){
        event.preventDefault();
    }

    $(this).data('toggle', !toggle);
});​​
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜