【问题标题】:A Selection Problem About Jquery一个关于 Jquery 的选择问题
【发布时间】:2009-06-13 13:37:30
【问题描述】:

在下面的代码中,当我单击 lnkSecc 时,我希望选择 lnkSecc 之后的第一个 div 下的复选框,其中 id 是 Grup。我该怎么做?

<td>Sipariş</td><td>
<a href="#" id="lnkSecc"  onclick="javascript:SelectSubCheckboxes(this);" >Seç/Kaldır</a>
</td><td>
<div id="Grup">
<table cellspacing="0" cellpadding="0" rules="all" border="0" id="dgrMenu__ctl6_dgrIslem" width="98%">
<tr>
<td align="Center" width="25"><font face="Verdana" size="1">&nbsp;</font></td>
</tr><tr>
<td align="Right"><font face="Verdana" size="1">
<input id="dgrMenu__ctl6_dgrIslem__ctl2_chkSec" type="checkbox" name="dgrMenu:_ctl6:dgrIslem:_ctl2:chkSec" />
</font></td>
</tr>
</table>
</div>
</td>
</tr><tr bgcolor="WhiteSmoke">
<td><b>Fatura</b></td><td><b>
<a href="#" id="lnkSecc"  onclick="javascript:SelectSubCheckboxes(this);" >Seç/Kaldır</a>
</b></td>
<td><b>
<div id="Grup">
</div>
</b></td>

【问题讨论】:

  • 您是否有多个具有相同 id 的元素(错误),或者是复制/粘贴处理不当?
  • 是的,我有相同的元素具有相同的 id,因为这是由 Asp.Net 中的数据网格提供的。

标签: jquery html checkbox selection


【解决方案1】:

我同意其他发帖者的观点,你真的应该将 lnkSeccGrup 更改为 CSS 类。

如果这些是来自 ASP.Net 数据网格的静态 HTML id,那么您使用的是模板列。在该模板列中更改静态 HTML 以发出类而不是 id 应该相对容易。

更改生效后,您的代码应如下所示:

// Format all of your hyperlinks when the page finishes loading
$(document).ready(function () {
    // For each hyperlink of CSS class lnkSecc
    $(".lnkSecc").click(function (e) {

        // Don't let the hyperlink navigate
        e.preventDefault();

        // Walk UP the DOM to the first TR, and
        // back down to the Grup CSS class, and then
        // its child checkboxes
        $(this).parents("tr").find(".Grup input:checkbox").each(function () {
            // Mark the found checkbox as checked
            this.checked = true;
        });
    });
});

【讨论】:

    【解决方案2】:

    首先,id 是指 html 页面上的唯一元素。永远不应该有两个具有相同 id 的元素。您应该使用类属性来区分相似类型/功能的元素。

    如果要遍历 DOM,则需要转到下一个 div grup 并找到所有后代类型复选框。

    查看 jQuery Traverse/Find api

    如果您确实将所有 id 更改为 class,示例代码将如下所示

     $(document).ready(function() {
        $("a.lnkSecc").click(function() {
            var children = $(this).next('div.Grup').find(':checkbox').get(0).checked=true;
        });
     });
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 2011-07-27
      • 2013-02-13
      相关资源
      最近更新 更多