【问题标题】:javascript get texts from element to arrayjavascript从元素到数组获取文本
【发布时间】:2013-11-18 11:50:58
【问题描述】:

我在将元素中的文本获取到数组时遇到问题。我试图“提取”的结构看起来像这样:

<div>
    text text text text
    <h2> title </h2>
    text2 text2 text2
    <img>
    <br>
    <br>
    text3 text3 text3 
    <h2> title 2</h2>
    text4 text4 text4
</div>

我要找的结果是数组:

['text text text', 'text2 text2 text2', 'text3 text3 text3', 'text4 text4 text4']

我无法编辑 HTML 结构。而且我不知道如何将这些数据放入数组中。我只尝试了 jquery 中的 .text() ,但这不是方法,而且我在 google 中没有找到任何帮助。

【问题讨论】:

  • 感谢您提供有关您在做什么的信息。我假设你有问题。请教我们这个问题:-p
  • 把你的文本放到一个标签里,比如 text text text 然后像 var array = $("span").split(" ");
  • 你对生成的html元素有控制权吗?

标签: javascript jquery html arrays dom


【解决方案1】:

您可以使用.contents().map() 创建解决方案

var arr = $('div').contents().map(function () {
    if (this.nodeType == 3) {
        var text = $.trim(this.nodeValue);
        if (text != '') {
            return text
        }
    }
}).get();

console.log(arr)

演示:Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 2016-03-09
    • 2015-09-07
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    相关资源
    最近更新 更多