开发者

Click Toggle (jQuery)

开发者 https://www.devze.com 2022-12-16 11:38 出处:网络
$(\"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?
$("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

精彩评论

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