jQuery用于解析HTML部分的函数

时间:2012-04-27 00:58:57

标签: jquery parsing

我正在寻找一个jQuery函数来解析HTML的一部分并从div class =“appArea”中的第一个<td>读取(存储在变量中)并继续读取HTML,直到它到达表格为止一类class =“tb_pages”,然后停止。

我认为我需要一个each()函数但无法使其工作。

<div class="appArea">

<p class="cstmTitle">Team Wilson</p>
<table width="100%" cellpadding="5" cellspacing="0" border="0">
<tr valign="top">
<td>

<p>
<p>We are proud to do our part to change the future and make a positive impact in the lives of others.</p>
<p><strong>Bullet List Ex</strong>:</p>
<ul>
<li>First</li>
<li>Second </li>
</ul>

<table class="tb_pages" border="0">
<thead>
<tr>
<th>Bacon</th>

3 个答案:

答案 0 :(得分:2)

丑:

var a = $('.appArea td:first').html().split('<table class="tb_pages"')[0];

var b = $('.appArea td:first').html().split(/<table(.*?)class="(.*?)tb_pages/)[0];

漂亮:

var c = $('div').append(
        $('.appArea td:first table.tb_pages').prevAll().clone()
    ).html();

选择你的毒药。

答案 1 :(得分:2)

我的“解决方案”有点不那么难看,但效率却很高:

var myHTML = "", isReading = false;

$(".appArea").children().each(function() {
    if(this.tagName == "td") isReading = true;
    else if($(this).hasClass("tb_pages") isReading = false;
    if(isReading) myHTML += $(this).html();
});

或者使用我最喜欢的if速记的解决方案,稍微更丑陋但效率稍高一些:

var myHTML = "", isReading = false;

$(".appArea").children().each(function() {
    this.tagName == "td" && (isReading = true);
    $(this).hasClass("tb_pages") && (isReading = false);
    isReading && (myHTML += $(this).html());
});

iambriansreed 的答案的替代方案,使用slice()代替split()(应该稍快一点,但同样难看):

var $fullHTML = $(".appArea").html()
var myHTML = fullHTML.slice(fullHTML.indexOf("<td>"), fullHTML.indexOf('<table class="tb_pages"'));

答案 2 :(得分:0)

$('div.appArea td:first table.tb_pages').prevAll()

将获取td内部但tb_pages表之前的所有内容。