简体   繁体   English

如何在 Java Script 中从 InsertItemTemplate 中找到控件

[英]How to find control from InsertItemTemplate in Java Script

I am new to Java Script.我是 Java Script 的新手。 I have a aspx ListView with InsertItemTemplate and some buttons in it.Now i need to access the buttons from insertitemtemplate in JavaScript to disable it.我有一个带有 InsertItemTemplate 和一些按钮的 aspx ListView。现在我需要从 JavaScript 中的 insertitemtemplate 访问按钮以禁用它。 This is not working?这是行不通的?

document.getElementById('<%= Button1.ClientID %>').disable = true; document.getElementById('<%= Button1.ClientID %>').disable = true;

Please help me.请帮我。

Solution 1解决方案1

You can set the Javascript code in code-behind, where you have access to the ClientID property of the controls for each item of the ListView.您可以在代码隐藏中设置 Javascript 代码,您可以在其中访问 ListView 的每个项目的控件的ClientID属性。 For example, if you have two buttons in the item template and you want to disable btn2 when clicking on btn1 , you can set the client code in the ItemDataBound event:例如,如果您的项目模板中有两个按钮,并且您想在单击btn2时禁用btn1 ,则可以在ItemDataBound事件中设置客户端代码:

void lstView_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.InsertItem)
    {
        Button btn1 = e.Item.FindControl("btn1") as Button;
        Button btn2 = e.Item.FindControl("btn2") as Button;
        btn1.OnClientClick = string.Format("var btn2 = document.getElementById('{0}'); btn2.disabled = true; return false;", btn2.ClientID);
    }
}


Solution 2解决方案2

If you cannot use the first method, but can modify the markup, then you can give the button a name that is unique in your page and set the ClientIDMode of the button to Static :如果您不能使用第一种方法,但可以修改标记,那么您可以为按钮指定一个在页面中唯一的名称,并将按钮的ClientIDMode设置为Static

<asp:Button ID="btnUniqueName1" runat="server" ClientIDMode="Static" ... />

Since there is at most one insert item in the ListView, that ID should be unique in the form.由于 ListView 中最多只有一个插入项,因此该 ID 在表单中应该是唯一的。 You can retrieve the button like this:您可以像这样检索按钮:

document.getElementById('btnUniqueName1');


Solution 3解决方案3

If you must find the button without modifying the server code, you can retrieve all the buttons in the form and look for some attribute that is found only in the button you are looking for:如果您必须在不修改服务器代码的情况下找到按钮,则可以检索表单中的所有按钮并查找仅在您要查找的按钮中找到的某些属性:

var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
    var button = buttons[i];
    // Check if that button is the one you want
    // Look for some unique attribute, class name, etc.
    if (button.className == 'btnUniqueClassName') {
        // The button was found
        button.disabled = true;
    }
}

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

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