简体   繁体   English

如何在代码隐藏文件中编写Javascript?

[英]How to write Javascript in the code behind file?

Below is the snapshot of my code that includes javascript taken from gridview's item template. 下面是我的代码的快照,其中包含从gridview的项目模板中获取的javascript。 It also has an image control placed. 它还具有图像控件。

  <ItemTemplate>
    <a href="javascript:ShowChildGrid('div<%# Eval("ID#") %>');">
                        <img id="imgdiv<%# Eval("ID#") %>" alt="Click" border="0" src="plus.gif" />
    </a> </ItemTemplate>

The JS function takes an argument as ID. JS函数将参数作为ID。 Now how can i write the JS in the code behind file? 现在我如何在代码隐藏文件中编写JS?

It is needed because i need to display the image based on some condition in row databound event of gridview. 这是需要的,因为我需要根据gridview的行数据绑定事件中的某些条件显示图像。

PS: I am aware of Register Startup Script and Client Script but i am not sure how would they fit in to satisfy my conditions. PS:我知道注册启动脚本和客户端脚本,但我不确定它们如何适应我的条件。

If you want to set the JS code for each single item of the gridview in RowDataBound-event, you could add a Hyperlink-control to your ItemTemplate and set the NavigationUrl-property of this control to the JS 如果要在RowDataBound-event中为gridview的每个单项设置JS代码,可以在ItemTemplate中添加一个Hyperlink-control,并将该控件的NavigationUrl-property设置为JS。

<ItemTemplate>
    <asp:Hyperlink runat="server" id="lnk" ImageUrl="..."/>
    ...
</ItemTemplate>

RowDataBound-eventhandler: 的RowDataBound-事件处理程序:

...
if (e.Row.RowType != DataControlRowType.DataRow)
    return;
string js = String.Format("javascript:ShowChildGrid('div{0}');", rowId);
var lnk = e.Row.FindControl("lnk") as Hyperlink;
if(lnk!=null)
{
    lnk.NavigationUrl = js;
    lnk.ImageUrl = ...;
}

Of course, you can also use a and img using the runat -Attribute 当然,你也可以使用aimg使用runat -Attribute

Change your template and use unobtrusive javascript. 更改您的模板并使用不引人注目的JavaScript。

<ItemTemplate>
    <button class="imgdiv-button" data-img-id='<%# Eval("ID#") %>'>
        <img class="imgdiv" alt="Click" border="0" src="plus.gif" />
    </button> 
</ItemTemplate>

$(".imgdiv-button").click(function() {
    ShowChildGrid($(this).data('img-id'));
});

Basically you want a button instead of a link (because it is a button). 基本上你想要一个按钮而不是一个链接(因为它是一个按钮)。 And you should just store that img-id in a data- attribute. 你应该将img-id存储在数据属性中。

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

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