Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - jQuery toggle() function not working

This question may be asked before. But I cant find the error. Here this is from the video tutorial of new boston.

$(document).ready(function(){
$('#btn').toggle(function(){
    $('#msg').html('yes');
},function(){
    $('#msg').html('No');
});
});

The video showing that when click first the div text is yes and next time it show no But when I try, when the page loads, the button fadeout and div show no. Why? There may be other methods to achieve this functionality. But why this dont work. He showing the syntax of toggle as

$('#btn').toggle(function(){code},function{code});
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

http://api.jquery.com/category/deprecated/

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed.

http://api.jquery.com/toggle-event/

Updated after OP's comment

DEMO

if you want to make this code work in any version of jQuery

$(document).ready(function () {
    var arr = ['yes', 'no'],
        i = 0;
    $('#btn').click(function () {
        $('#msg').html(arr[i++ % 2]);
    });
});

DEMO

if you want to make use of toggle-event like functionality in future

use .one()

$(document).ready(function () {
    function handle1() {
        $('#msg').html('yes');
        $('#btn').one('click', handle2);
    }

    function handle2() {
        $('#msg').html('no');
        $('#btn').one('click', handle1);
    }
    $('#btn').one('click', handle1);
});

or

Toggle was removed in version 1.9, so you cannot use it - if you want this logic can be manually implemented or you can make use of the migration plugin

to include the migration plugin, after the inclusion of jQuery library add

<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...