javascript 使用javascript停止按钮OnClick事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12789623/
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
Stopping button OnClick event with javascript
提问by Steven
I'm trying to run some javascript before my button's click event happens on the server side, but the javascript code runs, and the server side code runs right after that no matter what. Here's what I have:
我试图在我的按钮的单击事件在服务器端发生之前运行一些 javascript,但是 javascript 代码运行,并且服务器端代码无论如何都会在此之后运行。这是我所拥有的:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
SubmitClick = function() {
if ($("#<%= fuFile.ClientID %>").val() == "") {
$("#error").html("File is required");
return false;
}
}
});
</script>
<asp:FileUpload ID="fuFile" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClientClick="SubmitClick()" UseSubmitBehavior="false"
OnClick="btnSubmit_Click" />
<span id="error"></span>
I thought that setting UseSubmitBehavior="false"
and returning false
in the javascript function would work, but it's not. My error message gets displayed for a second before the server side code runs.
我认为在 javascript 函数中设置UseSubmitBehavior="false"
和返回false
会起作用,但事实并非如此。在服务器端代码运行之前,我的错误消息会显示一秒钟。
What am I doing wrong here?
我在这里做错了什么?
回答by Jeremy
Typically to cancel a client click you would add this return false;
通常要取消客户点击,你会添加这个 return false;
You can update your code to do this and it should work: OnClientClick="return SubmitClick();"
你可以更新你的代码来做到这一点,它应该可以工作: OnClientClick="return SubmitClick();"
回答by Jupaol
If you are using JQuery:
如果您使用的是 JQuery:
$btn.on("click", function (e) {
e.preventDefault();
}
回答by nick_w
What worked for me was:
Remove OnClientClick="SubmitClick()"
and set UseSubmitBehavior
back to true.
对我有用的是:删除OnClientClick="SubmitClick()"
并设置UseSubmitBehavior
回true。
Then change your $(document).ready()
method to
然后将您的$(document).ready()
方法更改为
$(document).ready(function () {
$('#btnSubmit').click(function () {
if ($("#<%= fuFile.ClientID %>").val() == "") {
$("#error").html("File is required");
return false;
}
return true;
});
});
回答by Sushanth --
You need to return the cancellation of the submitted behavior using return in OnClientClick event.
您需要在 OnClientClick 事件中使用 return 返回取消提交的行为。
try this
试试这个
OnClientClick="return SubmitClick()"