如何使用JavaScript逐行获取div内容? [英] How does one get div content line-by-line with Javascript?

查看:38
本文介绍了如何使用JavaScript逐行获取div内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要逐行处理< div> 的内容.缩短的片段看起来像这样:

I need to process the content of a <div> line-by-line. A shortened piece of it looks like this:

<div id='aoeu'>
    Ammonium NH%4^+ <br />
    Copper(I) Cu^+ <br />
    Gold(I) Au^+ <br />
    Rubidium Rb^+ <br />
    Acetone CH%3COCH%3 <br />
    Glycerin C%3H%5(OH)%3 <br />
</div>

我需要使用Java脚本分别处理每一行.

I need to work with each line individually with Javascript.

推荐答案

假定行"用换行符分隔,则可以执行以下操作:

Assuming that the "lines" are separated by newline characters you can do something like this:

​var el = document.get​ElementById("aoeu"),
    content = el.innerHTML.replace(/  |^\s+|\s+$/g,""),
    lines = content.split("\n");

也就是说,获取元素的 innerHTML ,删除开头和结尾的空格,然后在换行符上进行分割.

That is, get the innerHTML of the element, remove the leading and trailing whitespace, and then split on the newline character.

演示: http://jsfiddle.net/RG2WT/

现在,您已经添加了< br> 元素(尽管我将删除结尾的元素):

Now that you've added <br> elements (though I'd remove the trailing one):

var el = document.getElementById("aoeu"),
    content = el.innerHTML.replace(/^\s+|\s*(<br *\/?>)?\s*$/g,""),
    lines = content.split(/\s*<br ?\/?>\s*/);

也就是说,获取 innerHTML ,删除前导和后继空格以及任何尾随的< br> 元素,然后在其余的每个< br>上进行拆分; 元素及其周围的空白.

That is, get the innerHTML, remove leading and traling whitespace and any trailing <br> element, and then split on each remaining <br> element plus the whitespace around it.

演示: http://jsfiddle.net/RG2WT/3/

无论哪种方式, lines 都是一个数组,每个元素都是您的一行.无论哪种方式,我都将删除开头和结尾的空白,例如,第一项将是铵NH%4 ^ +" 而不是铵NH%4 ^ +" .

Either way lines will be an array with each element being one of your lines. Either way I'm removing leading and trailing white space so that, e.g., the first item will be "Ammonium NH%4^+" not " Ammonium NH%4^+ ".

这篇关于如何使用JavaScript逐行获取div内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆