2010-04-30 104 views
1

DOM結構如下所示(現有的網站......不能修改):文本的選擇部分在標籤

<table> 
<tr><td> 
<br><hr size="1"><strong>some heading 1</strong><br> 
<br>some text 1<br> 

<br><hr size="1"><strong>some heading 2</strong><br> 
<br>some text 2<br> 
</td></tr> 
</table> 

我想,這樣它看起來像這樣

<table> 
<tr><td> 
<br><hr size="1"><strong>some heading 1</strong><br> 
<br>some text 1<br> 
</td></tr> 
<tr><td> 
<br><hr size="1"><strong>some heading 2</strong><br> 
<br>some text 2<br> 
</td></tr> 
</table> 
操縱它

使用發佈的解決方案here,我可以獲得hr,strong,br標籤並將它們移動到新的td元素中。但是,由於它直接包含在td中並且在td上使用.text()會給我「一些文本1」以及「一些文本2」,所以我無法獲得「某些文本1」。

有什麼想法?

回答

2

您可以使用.contents()來收集包括文本節點的所有子節點。以下代碼搜索第二個小時(強健),並將前面的br和後面的所有內容移至新創建的td。我已經在谷歌瀏覽器中進行了測試。

$('table tr td').each(function() { 
    var firtHrSeen = false; 
    var indexOfSecondHr = -1; 
    var allChildren = $(this).contents(); 
    allChildren.each(function(index) { 
     if ($(this).is('hr')) { 
      if (firtHrSeen) { 
       indexOfSecondHr = index; 
       return false; // break out of each() 
      } else { 
       firtHrSeen = true; 
      } 
     } 
    }); 

    if (indexOfSecondHr != -1) { 
     var newTd = ($('<tr><td></td></tr>').insertAfter(this.parentNode))[0].firstChild; 
     allChildren.slice(indexOfSecondHr - 1).each(function(index) { 
      newTd.appendChild(this); 
     }); 
    } else { 
     // not found. something went wrong 
    } 
}); 
+0

謝謝!這做到了。我剛插入一個新的tr,並將新的td放在這個新的tr中。 – atlantis 2010-04-30 15:57:38

+0

我指的是基於myBB的線程的可打印版本。我想要做的是,將線程的每個響應放入其自己的行中,以便我可以根據用戶名來突出顯示某些行。 我試圖調整上述代碼以將其放入循環,以便所有響應由hr標籤分隔)被放入不同的行,但它給我奇怪的結果。如果您有任何見解,請告訴我。 – atlantis 2010-04-30 16:01:39

+0

我必須誤讀要求。我已更正了代碼,以便插入表格行而不是列。 – Arrix 2010-05-01 02:48:06

1

也許試試這個,這是不漂亮,但它應該工作...

html = $("table tr td").html(); 
someText1 = html.split("<br>")[3]; 
someText2 = html.split("<br>")[7]; 

這將會給你,你是無法解析出來的文字,你似乎有休息想通了。

+0

感謝您的回覆,但我不能使用上面的,因爲「一些文本1」實際上是可以包含'br'和其他標籤的論壇帖子的主體。 – atlantis 2010-04-30 12:09:05

0

是的,jQuery對文本節點沒有多大幫助。您經常需要使用常規的DOM方法。例如:

// Split on each `<hr>` inside a table cell except the first 
// 
$(mytablecell).children('hr').slice(1).each(function() { 
    // Create the next row 
    // 
    var rowi= mytablecell.parentNode.rowIndex; 
    var newrow= $(mytablecell).closest('table')[0].insertRow(rowi+1); 
    var newcell= newrow.insertCell(0); 

    // Move all nodes starting with the current `<hr>` into the next row 
    // 
    var node, next= this; 
    while (node= next) { 
     var next= node.nextSibling; 
     newcell.appendChild(node); 
    } 
}); 
+0

在parentNode發生異常。自從Arrix的代碼工作以來,沒有進一步探究。 – atlantis 2010-04-30 15:56:39

+0

parentNode應該沒問題。 'mytablecell'應該是一個DOM節點;如果它是一個jQuery包裝器,從它獲得一個'[0]'來獲得節點。 – bobince 2010-04-30 18:37:23

+0

這是一個jQ包裝。感謝您的更正。 – atlantis 2010-04-30 19:05:40