开发者

ASP.Button - OnClientClick firing incorrectly

I have a asp.net button 开发者_运维百科and I am using OnclientClick to close the window

<asp:Button ID="btnCancelSomething" runat="server" class="type-button" 
                    Text="Cancel"  OnClientClick = "Javascript:self.close()" 
                    onclick="btnCancelSomething_Click"/>

the onclick event does nothing and I am planning to remove it. However, when I click the button the first time it is loading the page again. I click the button again then the script is fired.

How to make the window close the first time?


If the button isn't going to have any server-side functionality behind it anyway, why make it an asp:Button at all? A regular button will do the trick just fine:

<input type="button" value="Cancel" class="type-button" onclick="self.close()" />

That way it's purely client-side, since that's all the functionality that's needed anyway. It won't cause any "post-back" unnecessarily.

You could even take it a step further and break apart markup from functionality:

<input type="button" value="Cancel" class="type-button" id="cancelButton" />

Then in a script tag elsewhere, or in a separate file:

$('#cancelButton').click(function() {
  self.close();
});

(Of course, this example assumes jQuery. But then what doesn't? The separation of markup and functionality if the key point here, though. How you achieve it, even how you identify the element with an id as in my example or some other way, is up to you.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜