如何提取html并将其添加到数组中
How to extract html and add them to the array?
我有一个关于上次发布的问题
如何从html标记中提取文本
Oriol的回答对我在表结构之间分离html标记有很大帮助。
然而,还有另一个问题。
var project =[''];
$('#htmlData').contents().each(function(){
if($(this).is('table')){
//do something with table
project.push['end of table']; //this line of codes is the problem....
}else{
project[project.length-1] += (
this.nodeType === 3 ? $(this).text() :
(this.nodeType === 1 ? this.outerHTML : '')
);
}
});
for(var i=0; i<project.length; ++i){
project[i] = project[i].replace(/'s+/g,' ') // Collapse whitespaces
.replace(/^'s/,'') // Remove whitespace at the beginning
.replace(/'s$/,''); // Remove whitespace at the end
}
假设我有html
数据,如以下
<em>first part</em> of texts here
<table>
......
......
</table>
<em>second part</em> of texts
我的项目数组最终如下:
//2 elements
('<em>first part</em> of texts here','end of table <em>second part</em> of texts)
但我想要的结果是
//3 elements
('<em>first part</em> of texts here','end of table','<em>second part</em> of texts)
如果选择器loop
到table
标记,则end of table
是我推送给array
的内容。
我该如何做到这一点?谢谢你的帮助!
问题是,在处理完表之后,您没有在数组中创建新位置。project.length-1在这种情况下总是指"表的末尾"位置,所以它只是将下一个"非表"数据与其连接起来。
试试这个:
var project =[''],
j = 0;
$('#htmlData').contents().each(function(){
if($(this).is('table')){
//do something with table
project.push('end of table'); //this line of codes is the problem....
j=project.length;
}else{
if (project[j] == undefined) project[j] = "";
project[j] += (
this.nodeType === 3 ? $(this).text() :
(this.nodeType === 1 ? this.outerHTML : '')
);
}
});
for(var i=0; i<project.length; ++i){
project[i] = project[i].replace(/'s+/g,' ') // Collapse whitespaces
.replace(/^'s/,'') // Remove whitespace at the beginning
.replace(/'s$/,''); // Remove whitespace at the end
}
console.log(project);
我相信有一个更干净的方法,但这应该会给你一个想法。
相关文章:
- 在函数中添加数组元素的数值
- 在Codrops的内容中添加数组元素展开缩略图网格预览
- 在javascript中动态添加数组数组
- 在 javascript 中添加数组到数组
- 如何使用推送在 JavaScript 中添加数组值
- 设置和添加数组值javascript时出现问题
- 使用 JavaScript 添加数组对象
- 将文件转换为数组并使用数据列表和选项标签为自动完成文本框添加数组元素
- 单击时将值推送到数组,然后循环添加数组值.Javascript
- 如何使用 JavaScript 更新或添加数组中的值
- 在窗体中动态添加数组文本框
- 在 javascript 中添加数组和对象会产生错误
- 如何在JavaScript中更新/添加数组的元素
- 在JavaScript中添加数组中的值
- 通过for循环添加数组值
- 如何在HTML中从Javascript添加数组的滚动列表
- Vaildate动态添加数组输入-jQuery Validate
- 在HighChart android中添加数组数据
- AngularJS:防止再次添加数组中已有的项
- 添加数组元素到现有的javascript数组