单击后如何禁用按钮以避免多个帖子请求?

时间:2012-12-13 10:49:01

标签: javascript asp.net

我想在点击几秒后禁用服务器端asp.net按钮控件&然后发起服务器端事件。我正在尝试使用setTimeout,但如果我使用setTimeout,则永远不会触发服务器端事件。有人可以帮忙吗?

   <script type="text/javascript">
    function disableBtn(btnId, dspTxt) {
        var btn = document.getElementById(btnId);
        btn.value = dspTxt;
        setTimeout(btn.disabled = true,1000);
    }
</script>

3 个答案:

答案 0 :(得分:1)

如何使用jQuery?

$('#buttonId').attr("disabled", true);

或在函数中

function disableBtn(btnId, dspTxt) {
  var button = $(btnId);
  button.attr("disabled", true);
  button.text(dspTxt);
}

http://www.w3schools.com/jsref/prop_select_disabled.asp

答案 1 :(得分:1)

在表单上放置两个按钮:

<asp:Button ID="ButtonToDisable" runat="server" Text="Button" />
<asp:LinkButton ID="PostBackLinkButton" runat="server" onclick="PostBackLinkButton_Click"></asp:LinkButton>

第一个是2秒后将被禁用的按钮,第二个是将进行回发的按钮。

接下来将此代码放在page.cs:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "timer",
               "setTimeout(function(){" + Page.ClientScript.GetPostBackEventReference(PostBackLinkButton, String.Empty) + "},2000)", true);
        }
    }

    protected void PostBackLinkButton_Click(object sender, EventArgs e)
    {
        ButtonToDisable.Enabled = false;
        ButtonToDisable.Text = "Button is disabled!";
    }

现在只需运行该页面并等待2秒钟即可发生回发并禁用PostBackLinkBut​​ton。

如果您不希望更新面板内的用户位置按钮可以看到回发。

答案 2 :(得分:1)

如果我正确理解你需要这样的东西:

 var isClicked=false;
 $('.myButton').click(function (e) {
    e=e?e:window.event;
    if(!isClicked){
        if($.browser.msie){e.cancelBubble=true; e.returnValue=false;}
      else
        e.preventDefault();
    isClicked=true;   
    $(this).attr('disabled','disabled');
    setTimeout(function(){delayClick();},1000);
  }

});
function delayClick()
{
   $(this).removeAttr('disabled');
   $('.myButton').click();

}