简体   繁体   English

动态设置输入按钮的asp.net

[英]asp.net setting onclick of input button dynamically

I have some dynamic buttons that look like this: 我有一些看起来像这样的动态按钮:

<input type="button" name="button" id="button" value="Click me"
    onclick="window.open('somelink');" />

I need to be able to change 'somelink' from the code behind. 我需要能够从后面的代码中更改“ somelink”。

How is that done? 怎么做? I know Request.Form["button"] gets the button but how to set the onlick property? 我知道Request.Form["button"]获取按钮,但是如何设置onlick属性?

add runat="server" and you can access that link from code behind 添加runat =“ server”,您可以从后面的代码访问该链接

<input runat="server" type="button" name="button" id="button" value="Click me"
    onclick="window.open('somelink');" />

and if you want to change the onclick attribute then you do this in code behind 如果要更改onclick属性,则可以在后面的代码中执行此操作

button.Attributes.Add("onclick", "window.open('someOtherLink');")

Changing the click handler on a button should be done when the page loads, not when the form is submitted. 应在页面加载时(而不是在提交表单时)更改按钮上的单击处理程序。 Before you can access your button from C#, you need to add runat="server" . 从C#访问按钮之前,需要添加runat="server" After that, you may access its properties: 之后,您可以访问其属性:

HTML 的HTML

<input runat="server" type="button" name="button" id="button" value="Click me"
    onclick="window.open('somelink');" />

C# C#

button.Attributes.Add("onclick", "window.open('[DynamicValueHere]');");

You can do this: 你可以这样做:

<asp:Button id="button" Text="Click me"  OnClick="window.open('somelink');" />

and
from code behind 从后面的代码

button.Attributes.Add("onclick", "window.open('somelink');");

And you can add whatever you want in place of somelink . 然后,您可以添加所需的任何内容来代替somelink
that's it. 而已。

你为什么不像这样的window.open(<%=SomeUrl%>)window.open内部传递<%=SomeUrl%>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM