javascript jQuery toggle() 函数不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18808112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery toggle() function not working
提问by Shameer
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 yesand next time it show noBut 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
视频显示,当第一次单击时,div 文本是yes,下次它显示no但是当我尝试时,当页面加载时,按钮淡出和 div 显示no。为什么?可能还有其他方法来实现此功能。但是为什么这不起作用。他将切换的语法显示为
$('#btn').toggle(function(){code},function{code});
回答by Tushar Gupta - curioustushar
http://api.jquery.com/category/deprecated/
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.
注意:此方法签名在 jQuery 1.8 中已弃用,并在 jQuery 1.9 中删除。jQuery 还提供了一个名为 .toggle() 的动画方法,用于切换元素的可见性。是否触发动画或事件方法取决于传递的参数集。
http://api.jquery.com/toggle-event/
http://api.jquery.com/toggle-event/
Updated after OP's comment
在 OP 评论后更新
if you want to make this code work in any version of jQuery
如果你想让这段代码在任何版本的 jQuery 中工作
$(document).ready(function () {
var arr = ['yes', 'no'],
i = 0;
$('#btn').click(function () {
$('#msg').html(arr[i++ % 2]);
});
});
if you want to make use of toggle-event
like functionality in future
如果你想toggle-event
在未来使用类似的功能
use .one()
使用.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
Toggle在 1.9 版本中被移除,所以你不能使用它 - 如果你想要这个逻辑可以手动实现或者你可以使用迁移插件
to include the migration plugin, after the inclusion of jQuery library add
包含迁移插件,在包含 jQuery 库后添加
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>