简体   繁体   English

通过VB.NET将click事件添加到按钮以激活javascript

[英]Adding click event to button to fire javascript, through VB.NET

I have an ASP.NET page which pulls a set of images from a database table, and using an enumerator, goes through all of them and displays then. 我有一个ASP.NET页面,它从数据库表中提取一组图像,然后使用枚举器遍历所有这些图像然后显示。

This all happens in the codebehind (VB.NET), where the code adds the placeholder and some controls inside tables (tables inside the placeholder). 这一切都发生在代码隐藏(VB.NET)中,其中代码添加占位符和表内的一些控件(占位符内的表)。

I've added a button to this placeholder (inside a table cell), all programatically, but how can I add a click event to the button programatically? 我已经以编程方式为这个占位符(在表格单元格内)添加了一个按钮,但是如何以编程方式向按钮添加单击事件? I want to fire a javascript (lightbox) which shows a large preview of the image (this works when the user clicks a small image, which invokes a string hyperlink on the code that points to the javascript). 我想触发一个javascript(灯箱),它显示图像的大预览(当用户点击一个小图像时,这会起作用,这个图像调用指向javascript的代码上的字符串超链接)。

cmdMyButton.attributes.add("onclick", "alert('hello');")

You can use the OnClientClick command to call client side javascript. 您可以使用OnClientClick命令来调用客户端javascript。 If your button was called btnMyButton, write your code as follows: 如果您的按钮名为btnMyButton,请按如下方式编写代码:

btnMyButton.OnClientClick = "window.open('http://www.myimage.com'); return false;";

using return false at the end will ensure the button doesn't cause a post back on the page. 在最后使用return false将确保该按钮不会导致页面上的回发。 replace the javascript with what you wanted to do. 用你想要的东西取代javascript。

An alternative to aboves would be 上面的替代方案将是

btnMyButton.Attributes.Add("onclick", "window.open('http://www.myimage.com'); return false;";

The preferred method of the .NET Framework to add an attribute (eg, onClick) to a webcontrol is: .NET Framework向webcontrol添加属性(例如onClick)的首选方法是:

control.Attributes.Add("onclick", "javascript:DoSomething('" + control.Value + "')")

You could also add the onClick event when another event is fired (eg, DataBound): 您还可以在触发另一个事件时添加onClick事件(例如,DataBound):

Private Sub ctlControlName_ActionName(ByVal sender As Object, ByVal e As System.EventArgs)
        Handles ctlControlName.ActionName
Dim control As ControlType = DirectCast(sender, ControlType)
control.Attributes.Add("onclick", "javascript:DoSomething('" + control.Value + "')")
End Sub

Hope this helps! 希望这可以帮助!

button.Attributes.Add("onclick", "javascript:fireLightBox()")

这是C#,但我认为VB.NET非常相似。

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

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