从第n个标签及以上获取html

时间:2018-02-06 11:48:58

标签: javascript jquery html

我有一张桌子......

        <table class="col-xs-12">
        <thead class="testhead col-xs-12">
            <tr class="col-xs-12" id="row1" style="color: white;">
                <th>0</th>
                <th>1</th>
                <th>2</th>
                <th>3</th>
                <th>4</th>
            </tr>           
        </thead>
        <tbody class="testbody col-xs-12">
            <tr class="testing col-xs-12" id="row0" style="color: white;">
                <td class="pTest">0 col 0</td>
                <td class="pTest">0 col 1</td>
                <td class="pTest">0 col 2</td>
                <td class="pTest">0 col 3</td>
                <td class="pTest">0 col 4</td>
            </tr>               

            <tr class="testing col-xs-12" id="row1" style="color: white;">
                <td class="pTest">1 col 0</td>
                <td class="pTest">1 col 1</td>
                <td class="pTest">1 col 2</td>
                <td class="pTest">1 col 3</td>
                <td class="pTest">1 col 4</td>
            </tr>

            <tr class="testing col-xs-12" id="row2" style="color: white;">
                <td class="pTest">2 col 0</td>
                <td class="pTest">2 col 1</td>
                <td class="pTest">2 col 2</td>
                <td class="pTest">2 col 3</td>
                <td class="pTest">2 col 4</td>
            </tr>               

            <tr class="testing col-xs-12" id="row3" style="color: white;">
                <td class="pTest">3 col 0</td>
                <td class="pTest">3 col 1</td>
                <td class="pTest">3 col 2</td>
                <td class="pTest">3 col 3</td>
                <td class="pTest">3 col 4</td>
            </tr>   

            <tr class="testing col-xs-12" id="row4" style="color: white;">
                <td class="pTest">4 col 0</td>
                <td class="pTest">4 col 1</td>
                <td class="pTest">4 col 2</td>
                <td class="pTest">4 col 3</td>
                <td class="pTest">4 col 4</td>
            </tr>                   
        </tbody>
    </table>

我想把它分成两个变量:

  • Var 1是TR的第一个x(自定义数量)
  • Var 2是TR的其余部分

我希望它也包含<tr>标签。

我尝试过使用jQuery nextAllnextUntil以及tr:gt(1),但它们并没有真正奏效。

例如,即使我将gt大于1,它只给我1 TR,它也排除了<tr>标签!

var hello = $(".testbody tr:gt(1)").html();
console.log(hello);

2 个答案:

答案 0 :(得分:1)

jQuery&#39; s .html()只获取第一个匹配元素的html。你需要遍历你的元素并自己组合html。

var hello = $('.testbody tr:gt(1)');
var html = '';
hello.each(function() {
    html = html + $(this).html()
});

例如。

编辑:.html()也只会获取内部html,而不是元素本身的标签/ html。您可能需要找出另一种方法

答案 1 :(得分:0)

试试这个,把它变成数组,像数组一样处理它:

Array.from($(".testbody tr")).slice(0,3).reduce((a,v)=>a+=v.outerHTML,'');
Array.from($(".testbody tr")).slice(3,$(".testbody tr").length).reduce((a,v)=>a+=v.outerHTML,'');