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
592 views
in Technique[技术] by (71.8m points)

jquery - Why doesn't returning false from OnClientClick cancel the postback

I have a LinkButton where I use the OnClientClick property to ask the user whether he really wants to perform an action, e.g:

<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:

<a id="ctl00_c1_content_btnDelete" onclick="return confirmDelete();"
 href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(..))"
... >
  Delete
</a>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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:

<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).


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

...