【问题标题】:How to pass GridView IDs and other controls into jQuery functions?如何将 GridView ID 和其他控件传递给 jQuery 函数?
【发布时间】:2015-12-22 19:07:37
【问题描述】:

我正在学习更多关于 jQuery 和 Javascript 的知识,我很喜欢它!使用这种语言,您对 Web 表单、控件等的强大能力胜过客户端-服务器方法!

人们使用脚本语言做的最常见的事情之一是控制 Gridview 的行和列。在我的情况下,我试图在另一个 gridview 的单元格中控制一个 Gridview。我想要做的是在子 GridView 控件中选中我所有的复选框。

这是我的主 GridView 和其中一列中的子 Gridview 的 ASP.net 代码:

        **<asp:GridView ID="gvStudents"** runat="server" DataSourceID="SqlDataSourceStudents" AutoGenerateColumns="False" Width="100%" OnRowDataBound="gvStudents_RowDataBound">
            <HeaderStyle BackColor="#5D7B9D" ForeColor="White" />
            <AlternatingRowStyle BackColor="#EEEEEE" />
            <RowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="Student" >
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("StudentName") %>' ToolTip='<%# Eval("ProgramName") %>'></asp:Label>
                    </ItemTemplate>
                    <ControlStyle Width="120px" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile" >
                    <ItemTemplate>
                        <asp:Label ID="lblMobile" runat="server" Text='<%# Eval("StudentMobilePhone") %>'></asp:Label>
                    </ItemTemplate>
                    <ControlStyle Width="70px" />
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <asp:CheckBox ID="cbNOKall" runat="server" Text="Next Of Kin" TextAlign="Left"/>
                    </HeaderTemplate>
                    <ItemTemplate>
                        **<asp:GridView ID="gvNOKs"** runat="server" AutoGenerateColumns="False" BorderStyle="None" GridLines="Vertical" ShowHeader="false" ShowFooter="false" BackColor="transparent" >
                            <Columns>
                                <asp:TemplateField HeaderText="Given Name" >
                                    <ItemTemplate>
                                        <asp:Label ID="lblNOKGivenName" runat="server" Text='<%# Eval("NOKname") %>'></asp:Label>
                                    </ItemTemplate>
                                    <ControlStyle Width="150px" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="NoK Type" >
                                    <ItemTemplate>
                                        <asp:Label ID="lblNOKType" runat="server" Text='<%# Eval("NOKType") %>'></asp:Label>
                                    </ItemTemplate>
                                    <ControlStyle Width="100px" />
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Mobile" >
                                    <ItemTemplate>
                                        <asp:Label ID="lblNOKMobile" runat="server" Text='<%# Eval("NOKMobile") %>'></asp:Label>
                                    </ItemTemplate>
                                    <ControlStyle Width="100px" />
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:TemplateField>
                                <asp:TemplateField>
                                    <ItemTemplate>
                                        <asp:CheckBox ID="cbNOKAdd" runat="server" onclick="javascript:SelectAllCheckboxesCol(this);" />
                                    </ItemTemplate>
                                    <ItemStyle HorizontalAlign="Center" />
                                </asp:TemplateField>
                           </Columns>
                        </asp:GridView>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Center" />
                    <ItemStyle HorizontalAlign="Left" />
                </asp:TemplateField>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <asp:CheckBox id="CheckBoxAll" runat="server" onclick="javascript:SelectAllCheckboxesCol(this);"/>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBoxAdd" runat="server" onclick="javascript:HighlightRow(this);"/>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

现在您可以看到,主 GridView 有一列复选框和一个标题复选框。

我控制这些复选框和每一行的突出显示如下:

    <script type="text/javascript" >
        //jQuery to select all checkboxes on the last column (4th column) of gvStudents
        function SelectAllCheckboxesCol(chk) 
        {
            var cBox = $('#<%=gvStudents.ClientID %> >tbody >tr >td:nth-child(4) > input:checkbox');
            cBox.attr('checked', chk.checked);  //check all the checkboxes
            cBox.click();                       //click them all to fire the Highlightrow() function. This un-ticks the checkboxes!
            cBox.attr('checked', chk.checked);  //re-check them again!
        }

        //jQuery to highlight a row selected
        function HighlightRow(chk) {
            var isChecked = chk.checked;
            var $selectedRow = $("#" + chk.id).parent("td").parent("tr");
            var selectedIndex = $selectedRow[0].rowIndex;
            var sColor = '';

            if(selectedIndex%2 == 0)
                sColor = '#EEEEEE';
            else
                sColor = 'white';

            if(isChecked)
                $selectedRow.css({
                    "background-color" : "Yellow",
                    "color" : "Black"
                });
            else
                $selectedRow.css({
                    "background-color" : sColor,
                    "color" : "Black"
                });
        }
</script>

我的问题是:

  • 如何使用“内部”GridView 来做同样的事情;并且,
  • 如何将 Gridview ID 传递给 jQuery 脚本和列号,而不必在脚本中硬编码以选中所有复选框?

感谢您的宝贵时间。

【问题讨论】:

    标签: javascript jquery asp.net parameter-passing controls


    【解决方案1】:

    首先,既然你是从Javascript / jQuery开始的,我给你一些建议:

    • 始终注意 ASP.NET 生成的 HTML 代码
    • 由于您将操纵NodesHTMLElements 等,因此了解它们很重要
    • 如果您不确定如何找到节点,请花点时间了解CSS selectors
    • 在学习 jQuery 之前学习纯 JavaScript/vanilla Javascript。知道自己在做什么总是好的
    • 看看style guides。例如,函数应命名为 camelCased。

    我已将您的函数更改为通用的,独立于父 GridView

    完整注释的代码如下。如果您有任何问题,请发表评论!

    function gridViewCheckAll(chk) {
      // parentNode of the chk is the td
      // parentNode of the td is the tr
      // parentNode of the tr is the tbody
      // children of the tbody is the trs
      var cell = chk.parentNode,
          row = cell.parentNode,
          tbody = row.parentNode,
          rows = tbody.children;
    
      // querySelectorAll to get all the td tags children of tr
      // and indexOf to get what is the index of the chk's td
      // note that I'm using the indexOf Array's method
      // I'm doing that since the property children is not an Array
      var index = [].indexOf.call(row.children, cell);
    
      // loop through the rows
      for (var i = 1; i < rows.length; i++) {
        // gets the current row, and gets the cell with the same index of the chk's cell
        // then, finds all the checkboxes inside it
        var checkBoxes = rows[i].children[index].querySelectorAll('input[type=checkbox]');
    
        // loops through the checkboxes and check/highlight them
        for (var j = 0; j < checkBoxes.length; j++) {
          checkBoxes[j].checked = chk.checked;
          highlightRow(checkBoxes[j]);
        }
      }
    }
    

    您可以使用 CSS 类而不是手动更改行颜色,而且更好的是,您可以为此使用 tr:nth-of-type(even)tr:nth-of-type(odd)

    您的HighLightRow 函数可以重写如下:

    function highlightRow(chk) {
      var row = chk.parentNode.parentNode;
      if (chk.checked)
        row.classList.add('selected-row');
      else
        row.classList.remove('selected-row');
    }
    

    那么,你应该有这样的 CSS:

    table.grid-view > tbody > tr {
      background-color: white;
    }
    
    table.grid-view > tbody > tr:nth-of-type(odd) {
      background-color: #EEE;
    }
    
    table.grid-view > tbody > tr.selected-row {
      background-color: yellow;
    }
    

    您需要将CssClass 属性放入您的GridView

    <asp:GridView ID="gvStudents" runat="server" CssClass="grid-view" (...)>
    

    并删除AlternatingRowStyleRowStyle,因为它们在每一行放置一个style 属性:

    <AlternatingRowStyle BackColor="#EEEEEE" />
    <RowStyle BackColor="White" />
    

    我有created a plunker for you,所以你可以使用上面的代码。

    【讨论】:

    • 还有一个问题... "row.classList[chk.checked ? 'add' : 'remove']('selected-row');" 是什么意思意思是? “添加”和“删除”状态来自哪里?再次感谢您的宝贵时间
    • ** 更新 ** 我只是将 var 从单个 var 引用(w3w 推荐的做法不是很好的做法)更改为单个 var,并且一切正常!哇...我想知道为什么带有逗号分隔变量的单个 var 会产生如此大的差异。这是我将其更改为... var cell = chk.parentNode; var row = cell.parentNode; var tbody = row.parentNode; var rows = tbody.children;
    • @Fernando68 关于row.classList[chk.checked ? 'add' : 'remove']('selected-row'); 行,这是我在答案中的简写:if (chk.checked) row.classList.add('selected-row'); else row.classList.remove('selected-row');。这是因为在 Javascript 中,您可以通过直接使用(例如 classList.add)或通过名称(例如 classList['add'])来使用类的属性/方法。我使用第二种方法只是为了编写更少的代码。
    • 再次感谢@Buzinas。只是让您知道它在 IE8 中不起作用,因为不支持 classList。我正在尝试使用 className 修改该行。关于此的任何提示,因为我认为 className 只是一个字符串属性,而不是一个列表。
    • @Fernando68 你可以抛出一个classList polyfill - 比尝试为恐龙浏览器编写代码更好,你不觉得吗?您甚至可以使用 IE 的 if 标签添加它:&lt;!--[if lte IE 9]&gt;&lt;script src="classList.js"&gt;&lt;/script&gt;&lt;![endif]--&gt;
    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2020-06-27
    • 2012-03-07
    相关资源
    最近更新 更多