javascript
  • jquery
  • html
  • css
  • 2011-08-02 50 views 0 likes 
    0

    我有一个有几行的html表 - 可以说这个例子是17。在第2,9和15行,我有一些BOLD文本,它们之后的行基本上是标题。我用下面的代码的每个报头之后添加一个IMAGE:jquery,在表中选择几个TR

    $("#tblResults tr.lGreyBG td span.gridTXT b").each (function(index) { 
        $(this).after("&nbsp;<img class='ChartButton' id='c"+ index +"'src='Images//chart_bar.png' alt='Chart' width='20' />");     
    }); 
    

    我也有以下的代码位,其结合一个点击事件到每个图表的按钮。

    $("img.ChartButton").click(function(){ 
        alert ($(this).attr("id")); // THIS LINE WILL BE REPLACED 
    }); 
    

    此刻,它只是显示图表按钮的ID。我需要做的是替换警报,以便将点击后的标题行之后的行拖回到下一个标题行,直到表结束(以先到者为准)。所以如果点击第一个按钮,那么第3到第8行将被撤回。一旦我有了这些,我可以遍历每个TD单元来查看表中的数据。

    非常感谢任何帮助,我需要用什么“选择器”来拉回正确的行。还要注意,这需要是动态的,因为其他表将具有不同的行数。

    感谢 ^ h

    回答

    1
    // notice that use after() directly, without each() 
    $("#tblResults tr.lGreyBG td span.gridTXT b").after(function (index) { 
        return "<img class='ChartButton' id='c"+ index +"'src='Images//chart_bar.png' alt='Chart' width='20' />"; 
    }); 
    
    $("#tblResults").delegate("img.ChartButton", "click", function() { 
        var currentRows = $(this).closest("tr").nextUntil("tr:has(span.gridTXT b)"); 
    }); 
    

    BTW:你一定要考虑使用多个<thead>,如果你的表有多个头部和身体<tbody>标签更语义标记。

    $("#tblResults thead span.gridTXT b").after(function (index) { 
        return "<img class='ChartButton' id='c"+ index +"'src='Images//chart_bar.png' alt='Chart' width='20' />"; 
    }); 
    
    $("#tblResults").delegate("img.ChartButton", "click", function() { 
        var currentRows = $(this).closest("thead").next("tbody").find("tr"); 
    }); 
    

    编辑:更改答案使用nextUntil()

    +0

    感谢点出了 “每个()” 的部分,理解。 currentRows行也拉回我需要的确切行。现在我可以尝试迭代每个TD并从中获取数据:) – harag

    2

    如果有一组属于一起的行,我的第一个直觉就是声明可以帮助我一次选择所有行的类,例如,

    <tr class="group-1"> ... </tr> 
    <tr class="group-1"> ... </tr> 
    <tr class="group-2"> ... </tr> 
    <tr class="group-2"> ... </tr> 
    ... 
    

    或Tomalak建议的多个theads和tbodies。

    如果这是不可能的,你想使用jQuery来做到这一点,你可以使用nextAll()选择标题后面的所有行。您只需过滤掉下一个标题之后的所有行。

    var nextBlockAndTheRest = $(this). // create jQuery object out of this img 
              closest("tr"). // find the parent tr 
              nextAll("tr.lGreyBg"). // find all next lGreyBg rows 
              first("td span.gridTXT b"). // find the first with b 
              nextAll(). // select all following rows 
              andSelf(); // add the row with b 
    
    var thisBlock = $(this). // create jQuery object out of the img 
           closest("tr"). // find the parent tr 
           nextUntil("td span.gridTXT b"). // select everything after the tr 
           andSelf(). // add the current block heading 
           not(nextBlockAndTheRest); // remove all the rest of the rows 
    

    jsFiddle

    +0

    对于'nextUntil()'+1而言 - 没有想到这一点。 – Tomalak

    +0

    +1我已经给出了完整的横向信息+1。非常感谢。但是,Tomalak“currentRows”行为我拉回了正确的行。不幸的是,我不能修改表格布局以排除几个“组”或theads。多数民众赞成在与其他人民的旧问题代码:( – harag

    相关问题