在jQuery中读取元素的每一行

时间:2010-04-07 14:01:10

标签: javascript jquery html css

假设我有这个html标记:

<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 个答案:

答案 0 :(得分:15)

你的意思是这样的:

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

因为这是文本(而不是html),所以你应该这样对待它。唯一的方法是读取它然后使用字符串解析例程。

答案 1 :(得分: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

有些浏览器会修剪第一个换行符,有些则不会,所以有几个边缘情况(没有双关语)。但基本上就是这样。