首页 > 解决方案 > 将 div 文本添加到数组

问题描述

我需要将此<div><a href="">Test</a>and another <a href="">Test</a></div>文本添加到这样的数组中:['Test', 'and another', 'Test'],但结果是['Test', 'Test'],“和另一个”文本被忽略。

let text = [];
$('div').children().each(function () {
  text.push($(this).text());
});

标签: jqueryhtml

解决方案


正如这里所解释

.children() 只返回 html 元素而不是文本,所以很明显,另一个不包含在项目中。为了达到您想要的结果,您可以简单地将它放在<span>标签中:)


推荐阅读