2012-06-02 40 views
10

快速的问题,大家好,我似乎无法得到这个。对()切换在这里一起工作

$('#wrap').on('toggle', '#image', function(){ 
    <!-- Do stuff --> 
    }); 

,以便能够在其内部都有一个切换?有任何想法吗?我尝试了谷歌搜索,但没有运气。

这就是我试图让与。对工作的代码,因为目前它不更改应用到所有元素儿子页,(有#image和#brick)

$("#result_options").toggle(function() { 
     var image_width = $('#image').width()/2; 
     var brick_width = $('#brick').width()/2; 
     $("#image").css("width",image_width); 
     $("#image").css("padding","4px"); 
     $("#brick").css("width",brick_width); 
    },function(){ 
     $("#image").css("width","300"); 
     $("#image").css("padding","8px"); 
     $("#brick").css("width","314"); 
     $(this).html("Smaller Results"); 
    }); 
}); 
+1

的可能重复[使用jQuery .live与切换事件](http://stackoverflow.com/questions/2172614/using-jquery-live-with-toggle-event) – j08691

回答

24

您面临的问题是没有toggle事件; toggle()是一个jQuery方法。要实现toggle(),与on()我认为你需要使用click事件,然后一个if语句来测试的东西是否一直处于开启状态,或切换关/不被切换

$('#wrap').on('click', '#image', function(){ 
    if (!$(this).attr('data-toggled') || $(this).attr('data-toggled') == 'off'){ 
     /* currently it's not been toggled, or it's been toggled to the 'off' state, 
      so now toggle to the 'on' state: */ 
      $(this).attr('data-toggled','on'); 
      // and do something... 
    } 
    else if ($(this).attr('data-toggled') == 'on'){ 
     /* currently it has been toggled, and toggled to the 'on' state, 
      so now turn off: */ 
      $(this).attr('data-toggled','off'); 
      // and do, or undo, something... 
    } 
}); 
+0

@maryisdead:谢谢!我没有意识到(或者我认为它被用作用户定义的自定义事件)。 =) –

+1

不客气!谢谢您的回答! :-) – maryisdead