使用jquery或javascript在GridView的TemplateField中查找控件

问题描述 投票:0回答:1

在客户端按钮单击事件,我想获得位于网格视图的项目模板中的控件ID。我尝试了这段代码,但它不起作用。谢谢

function buttonClicked(sender, args) {
    var gv = $find('<%= GridView1.ClientID %>');

    var textbox = $GridView1.findControl(gv.get_element().parentNode, "Textbox");
}

这是Gridview

<form id="form1" runat="server">
   <asp:ScriptManager ID="ScriptManager1"runat="server">
   </asp:ScriptManager>
   <div>
     <asp:UpdatePanel ID="upTest" runat="server">
      <ContentTemplate>
        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="KurzDS" DataKeyNames="Id" OnRowCommand="GridView1_RowCommand">
          <Columns>
            <asp:TemplateField>
              <ItemTemplate>
                <asp:TextBox ID="Textbox" runat="server" Text="Textbox"></asp:TextBox>
              </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
              <ItemTemplate>
                <asp:TextBox ID="Textbox1" runat="server" Text="Textbox1"></asp:TextBox>
              </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
              <ItemTemplate>
                <asp:Button ID="btn" Text='btn' CommandArgument='<%# Eval("Id")%>'  CommandName="btn" runat="server" CausesValidation="false" />
              </ItemTemplate>
            </asp:TemplateField>
          </Columns>
        </asp:GridView>
      </ContentTemplate>
    </asp:UpdatePanel>
   </div>
</form>
c# jquery asp.net gridview itemtemplate
1个回答
0
投票

感谢您加入GridView示例。现在,我可以看到你在尝试什么,我有一个更好的答案给你。

首先,对按钮模板稍作更改,为CommandArgumentand更改OnClientClick,因为您使用此按钮客户端而不是回发到服务器,您可以像这样简化它:

<asp:Button ID="btn" Text='btn' OnClientClick='<%# Eval("ID", "YourJavascriptFunction({0} - 1); return false;") %>' runat="server" CausesValidation="false" />

我有click事件调用你的JavaScript函数,它发送服务器端解析id的参数。注意我先减去1。这是因为服务器端ASP.Net Eval函数给出了从1开始的ID。但是,为文本输入元素生成的每个id都以零基数开头。

现在看看下面的JavaScript函数。

// Clicking the first button sends in a 0, second sends in a 1, etc.
function YourJavascriptFunction(id) {
  // each of the TextBox1 elements has an ASP.Net server side
  // generated id that ends with GridView2_Textbox1_0,
  // GridView2_Textbox1_1, etc.
  let selectId = "input[id$='GridView2_Textbox1_" + id + "']";

  // The text we use in the querySelector function states
  // find the DOM element with a tag of "input" where the id
  // ends with . . . The $ in id$= is the part that says the
  // value must "end with"
  let textBox1 = document.querySelector(selectId);

  // Now that we have TextBox1 from the same row as the button, 
  // getting the value is easy.
  alert(textBox1.value);
}

我没有使用jQuery示例,因为这个querySelector命令几乎适用于包括IE8及以上版本在内的所有浏览器,所以你不需要jQuery这么简单。

如果我能进一步帮助,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.