jQuery 为什么不从 OnClientClick 返回 false 取消回发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6812168/
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
Why doesn't returning false from OnClientClick cancel the postback
提问by M4N
I have a LinkButton
where I use the OnClientClick
property to ask the user whether he really wants to perform an action, e.g:
我有一个LinkButton
我使用OnClientClick
属性来询问用户他是否真的想要执行某个操作的地方,例如:
<script>
function confirmDelete() {
return confirm('Do you really want to delete?');
}
</script>
<asp:LinkButton runat="server" OnClientClick="return confirmDelete()" ... />
This pattern usually works, but on this specific page, it doesn't. No matter whether I click OK or Cancel in the confirm dialog, the postback is executed.
这种模式通常有效,但在这个特定页面上,它不起作用。无论我在确认对话框中单击确定还是取消,都会执行回发。
Just for completeness (to answer pst's question): the rendered HTML is OK. E.g. it looks like this:
只是为了完整性(回答 pst 的问题):呈现的 HTML 没问题。例如它看起来像这样:
<a id="ctl00_c1_content_btnDelete" onclick="return confirmDelete();"
href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(..))"
... >
Delete
</a>
采纳答案by M4N
The reason for the behavior was another piece of javascript, where a handler for the link(button)'s click event was registered via jquery, e.g. something similar to this:
该行为的原因是另一段 javascript,其中链接(按钮)的点击事件的处理程序是通过 jquery 注册的,例如类似于以下内容:
<script>
$(document).ready(function() {
$('a').click(function() {
// ...
return (someCondition == true);
});
});
</script>
It seems this click-handler was called after the one registered by OnClientClick
, and when this one returned true
, then the postback occurred, independent of the result of the first click-handler (the confirm dialog).
似乎这个点击处理程序是在由 注册的那个之后调用的OnClientClick
,当这个返回时true
,回发发生,独立于第一个点击处理程序(确认对话框)的结果。
回答by maxspan
Here is something which worked for me.
这是对我有用的东西。
<asp:LinkButton runat="server" OnClientClick="return (!confirmDelete()){return false;}" />
Javascript
Javascript
function confirmDelete(){
if(something == true){
return true;
}
else{
return false;
}
}