一键打开一个窗口(aspx页面)+ javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3999342/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:07:17  来源:igfitidea点击:

open a window (aspx page) with one click + javascript

javascriptclick

提问by BumbleBee

I need to open a new window with a single clickof an asp.net button. My problem is that it always takes two clicks.. if i write the open window code in the page load, then the window gets open on 1 click.. any ideas how to get around this...

我需要单击一个 asp.net 按钮来打开一个新窗口。我的问题是它总是需要点击两次..如果我在页面加载中编写打开窗口代码,那么窗口会在一次点击时打开..任何想法如何解决这个问题......

Button Click Code :

按钮点击代码:

btnClaim.Attributes.Add("Onclick","javascript:return OpenPopup()")

Javascript function :

Javascript 函数:

  function OpenPopup()
{
window.open("newWindow.aspx?", "_blank", "height=500, width=575, left=150,
top=150, " +
"location=no, menubar=no, resizable=no, " +
"scrollbars=no, titlebar=no, toolbar=no", true);
}  

回答by Guffa

The problem is that you are adding code to handle a click in the click event handler. That means that when you click the button the first time the event handler adds the attribute to the button. After the postback you can click the button again to open the popup, as the button now has the client side code.

问题是您正在添加代码来处理单击事件处理程序中的单击。这意味着当您第一次单击按钮时,事件处理程序会将属性添加到按钮。回发后,您可以再次单击该按钮以打开弹出窗口,因为该按钮现在具有客户端代码。

Either add the attribute in Page_Load so that the button always has the attribute, or in the event handler add code to the page that calls the function immediately after postback:

在 Page_Load 中添加属性以便按钮始终具有该属性,或者在事件处理程序中将代码添加到在回发后立即调用该函数的页面:

ClientScript.RegisterStartupScript(Me.GetType(), "open", "OpenPopup();", True)

回答by jordanbtucker

This problem likely occurs because the form in being submitted on click (PostBack). If you return false in the onclick attribute, it should cancel a form submit. You can also use OnClientClick.

出现此问题的原因可能是表单在单击 (PostBack) 时提交。如果在 onclick 属性中返回 false,则应取消表单提交。您还可以使用OnClientClick

btnClaim.OnClientClick = "javascript:OpenPopup(); return false;";