Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

jquery - .on() & toggle working together

Quick question here guys, I cant seem to get this

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

to be able to have a toggle inside it? Any ideas? I have tried googling but with no luck.

this is the code i am trying to get to work with .on, as currently it doesn't apply the changes to all of the element son the page, (that have #image and #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");
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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...
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...