[英]How to know when a function jQuery has completed
I have a piece of jQuery and I can't get it done. 我有一块jQuery,但我做不到。 I have 2 bulletproof vest images.
我有2个防弹背心图片。 When a button is clicked, 1 will show up.
单击按钮时,将显示1。 When another is clicked, all vests have to be hidden again first.
单击另一个后,必须首先再次隐藏所有背心。 Now the vests both show up and then 1 disappears.
现在,背心都出现了,然后消失了1个。
Here is my example: http://bykwien.nl/soldier/voorbeeld.html 这是我的示例: http : //bykwien.nl/soldier/voorbeeld.html
Full preview on JSFiddle: http://jsfiddle.net/8DPCf/ 关于JSFiddle的完整预览: http : //jsfiddle.net/8DPCf/
$('#vest1').click(function(){
$('.vest').addClass('hide', function(){
$('.vest1').removeClass('hide');
})
});
$('#vest2').click(function(){
$('.vest').addClass('hide', function(){
$('.vest2').removeClass('hide');
})
});
Just remove the callbacks will make the whole thing work, see here: 只需删除回调即可使整个工作正常进行,请参见此处:
http://jsfiddle.net/8DPCf/1/ http://jsfiddle.net/8DPCf/1/
$('#vest2').click(function(){
$('.vest').addClass('hide', function(){
$('.vest2').removeClass('hide');
})
});
becomes 变
$('#vest2').click(function(){
$('.vest').addClass('hide');
$('.vest2').removeClass('hide');
});
According to the jQuery documentation , the addClass
method has no callback parameter, which it also doesn't need because it doesn't do anything asynchronically. 根据jQuery文档 ,
addClass
方法没有回调参数,该参数也不是必需的,因为它不会异步执行任何操作。
Quick Fix 快速解决
I don't think you need to use any callback function for this, just do the 2 calls sequentially like so: 我认为您不需要为此使用任何回调函数,只需依次执行以下两个调用即可:
$('#vest1').click(function(){
$('.vest').addClass('hide');
$('.vest1').removeClass('hide');
});
$('#vest2').click(function(){
$('.vest').addClass('hide');
$('.vest2').removeClass('hide');
});
Here is a working example 这是一个有效的例子
Advanced Solution 进阶解决方案
In order to make it more generic, allowing for x number of vests you could create a single event handler and determine the vest class using the id
of the clicked button... 为了使其更通用,允许使用x个背心,您可以创建一个事件处理程序,并使用clicked按钮的
id
确定背心类...
Change your button HTML like so (added class): 像这样更改按钮的HTML(添加的类):
<div class="item-checkbox vest-button" id="vest1"></div>
<div class="item-checkbox vest-button" id="vest2"></div>
And your javascript as follows: 和你的JavaScript如下:
//add event to all vest elements, and use this to determine which one is clicked
$('.vest-button').click(function(){
$('.vest').addClass('hide');
var className = '.' + $(this).attr("id");
$(className).removeClass('hide');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.