2010-04-07 30 views
6

假設我有這樣的HTML標記的每一行:JQuery的:讀一個元素

<div id="wrapper"> 
<pre class="highlight"> 
    $(function(){ 
    // hide all links except for the first 
    $('ul.child:not(:first)').hide(); 
    $("a.slide:first").css("background-color","#FF9900"); 

    $('ul.parent a.slide').click(function(){ 
     $('ul.parent a.slide').css("background-color","#3399FF"); 

     $('ul.parent a.slide').mouseout(function(){ 
      $(this).css("background-color","#3399FF"); 
     }); 

     $('ul.parent a.slide').mouseover(function(){ 
      $(this).css("background-color","#66CC66"); 
     }); 
    }); 
    }); 
    </pre> 
</div> 

什麼是閱讀存在於DIV代碼的每一行的最簡單的方法。如何以任何我想要的方式從每個線樣式的div或循環中提取每行代碼。

感謝

編輯:

我已經包裝類後加入pre標籤,請考慮之謂也。由於

+2

我假設你在''wrapper'的CSS中有'white-space:pre'或其他什麼東西? – 2010-04-07 14:05:37

+1

這是邪惡的最純粹的形式。 – googletorp 2010-04-07 14:11:55

+0

@ T.J。克勞德:是的,我有。 – Sarfraz 2010-04-07 14:14:54

回答

15

你的意思是這樣的:

var lines = $("#wrapper pre").text().split("\n"); 
$.each(lines, function(n, elem) { 
      console.log(elem); 
      }); 

由於這是文本(而不是HTML),你應該把它看作。要做到這一點的唯一方法是閱讀它,然後使用字符串解析例程。

+0

請查看我的新編輯問題。謝謝 – Sarfraz 2010-04-07 14:16:26

3

大多隻是需要直接的JavaScript:

var text; 

text = $('#wrapper pre').text(); // Or .html, doesn't really matter with the input you showed 
text = text.replace("\r\n", "\n"); // Just in case 
text = text.split("\n"); 
// text is now an array of lines 

一些瀏覽器將修剪第一線斷裂,有些不會,所以有一對夫婦的邊緣的情況下(沒有雙關語)。但基本上就是這樣。

+0

請看我的新編輯問題。謝謝 – Sarfraz 2010-04-07 14:16:49