.on() & toggle working together

前端 未结 1 671
刺人心
刺人心 2020-12-09 12:40

Quick question here guys, I cant seem to get this

$(\'#wrap\').on(\'toggle\', \'#image\', function(){
    
  });

to

相关标签:
1条回答
  • 2020-12-09 13:13

    The problem you're facing is that there is no toggle event; toggle() is a jQuery method. To implement a toggle(), with on() I think you'd need to use a click event, and then an if statement to test whether something's been toggled on, or toggled-off/not-toggled

    $('#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 讨论(0)
提交回复
热议问题