Javascript 如何在 Jquery 中的 click() 之后调用一个动作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6485968/
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
How to call an action after click() in Jquery?
提问by rogeliog
I want to load an image and some other actions after I click a certain DOM element, but I want to load them AFTER the clicking action finished.
我想在单击某个 DOM 元素后加载图像和其他一些操作,但我想在单击操作完成后加载它们。
Here is a code example:
这是一个代码示例:
$("#message_link").click(function(){
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
});
The problem is that the if condition executes before the click action have finished(Or at least that is my impression). I need that the If condition executes after the click action has finished. Can some one please tell me a solution?
问题是 if 条件在点击操作完成之前执行(或者至少这是我的印象)。我需要在单击操作完成后执行 If 条件。有人可以告诉我一个解决方案吗?
Thanks :)
谢谢 :)
采纳答案by James Allardice
If I've understood your question correctly, then you are looking for the mouseup
event, rather than the click
event:
如果我正确理解了您的问题,那么您正在寻找mouseup
事件,而不是click
事件:
$("#message_link").mouseup(function() {
//Do stuff here
});
The mouseup
event fires when the mouse button is released, and does not take into account whether the mouse button was pressed on that element, whereas click
takes into account both mousedown
and mouseup
.
该mouseup
事件在释放鼠标按钮时触发,并且不考虑鼠标按钮是否在该元素上按下,而同时click
考虑mousedown
和mouseup
。
However, click
should work fine, because it won't actually fire until the mouse button is released.
但是,click
应该可以正常工作,因为在释放鼠标按钮之前它实际上不会触发。
回答by Kevin Decker
setTimeout
may help out here
setTimeout
可能会在这里有所帮助
$("#message_link").click(function(){
setTimeout(function() {
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
}, 100);
});
That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.
如果满足 some_conditions,这将导致在单击事件发生后约 100 毫秒附加 div。
回答by hrnsky
you can write events on elements like chain,
您可以在链等元素上编写事件,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
我用它来删除购物车项目。同一个对象,做一些动作,一个动作之后