2014-12-03 25 views
-2

我有以下的html代碼。將HTML元素的文本發送到數組

<!DOCTYPE html> 
<html>  
    <body> 

     <div> 
      <h1>My First Heading</h1> 
      <p>My first paragraph.</p> 
     </div> 

     <div id="1"> 
      <p id="2">Paragraph First 
       <ol id="3"> 
        <li id="4">alice 
         <ul id="31"> 
          <li id="41">bob</li> 
          <li id="51">foo</li> 
          <li id="61">grow</li> 
         </ul> 
        </li> 
        <li id="5">coding</li> 
        <li id="6">fun</li> 
      </ol> 
      </p> 
     </div> 

     <div> 
      <p>Paragraph Second</p> 
     </div> 


    </body> 
</html> 

我想獲取所有元素的文本到一個數組(預序橫向優先)。 因此,對於下面的例子陣列由,

[My First Heading, first paragraph, Paragraph First, alice, bob, foo, grow, coding, fun] 

如果needsHow我可以使用jQuery。我可以做到這一點嗎?

我自己的非工作嘗試

var root = document.documentElement; 
recursivePreorder(root); // Recusively find and handle all text nodes 
function recursivePreorder(node) { 
    // If node is a text node 
    if (node.type == 3) { 
    //add to the array 
    } // else recurse for each child node 
    else {  
    for(var i=0; i<node.childNodes.length; i++)  
     recursivePreorder(node.childNodes[i]); 
    } 
} 

UPDATE

當我的標籤是<li id="41">bob<a href="url">link text</a>alice</li>它給了我爲[bob, link text, alice]。但我想輸出爲[bob<a href="url">link text</a>alice]意味着鏈接正常工作。這是我目前的解決方案,

var arr=$('body').find('*').contents().filter(function() { return this.nodeType === 3&&this.textContent.trim()!=""; }); 

如何解決這個問題?

+0

你嘗試過自己的東西??? – 2014-12-03 05:54:24

+0

最短的:http://stackoverflow.com/a/7824394/295783 – mplungjan 2014-12-03 06:00:45

+0

@Kartikeya是的。以下是我糟糕的解決方案。 'var root = document.documentElement; recursivePreorder(root); // Recusively找到並處理所有文本節點 功能recursivePreorder(節點){ //如果節點是一個文本節點 如果(node.type == 3){// 添加到數組 } //別的爲每個子節點遞歸 else { for(var i = 0; i 2014-12-03 06:02:00

回答

0

您可以使用map()

$(document).ready(function() { 
    var arr = $("#container *").contents().map(function() { 
     if (this.nodeType === 3 && this.textContent.trim() != "") { 
      return this.textContent.trim(); 
     } 
    }); 

    console.log(arr); 
}); 

nodeType將3文本內容

Demo

+0

謝謝你的回答。對不起,我不給我陣列。當我記錄arr.length它輸出0.你能幫我解決它嗎? – 2014-12-03 06:24:18

+0

檢查這個小提琴http://jsfiddle.net/anoopjoship/60xL3zfu/6/ – 2014-12-03 06:25:41

+0

@ coding7891將代碼包裝在文檔中。準備好了\ – 2014-12-03 06:26:58

0

試試這個:

var arr = []; 
$(document).find('li,p,h1').each(function(e){ 
    arr.push(($(this).clone().children().remove().end().text()).trim()); 
}) 

Demo

+0

太好了。鏈接似乎分開了雙方的文字內容。如何避免它? – 2014-12-03 09:06:58

+0

你有沒有嘗試過避免它? – 2014-12-04 05:06:39