是否有一种简单的方法可以使用jquery / javascript从字符串(html)中获取数组:
HTML:
<h1>this is a test</h1>
<p>This is a test</p>
<p>This is a test</p>
<h2>this is a test</h2>
<p>This is a test</p>
到一个数组:
array[0]['tag'] = 'h1'
array[0]['value'] = 'this is a test'
array[1]['tag'] = 'p'
array[1]['value'] = 'this is a test'
array[2]['tag'] = 'p'
array[2]['value'] = 'this is a test'
array[3]['tag'] = 'h2'
array[3]['value'] = 'this is a test'
array[4]['tag'] = 'p'
array[4]['value'] = 'this is a test'
谢谢!
答案 0 :(得分:2)
更新
JS
var htmlstring = "<h1>this is a test</h1><p>This is a test</p><p>This is a test</p><h2>this is a test</h2><p>This is a test</p>",
map = { };
$(htmlstring).each(function(_, node) {
map[ _ ] = { };
map[ _ ][ node.nodeName ] = node.textContent;
});
console.log(map);
答案 1 :(得分:2)
这样的事情应该可以做到这一点,但它不会递归地起作用(仅适用于直接的身体儿童)。
var tags = [];
$('body').children().each( function( index, element ) {
tags.push({
'tag' : element.nodeName.toLowerCase(),
'value' : element.text()
});
});
答案 2 :(得分:0)
这是一个想法
$('body *').each(function(i){
console.log($(this).text());
console.log(this.nodeName);
console.log(i);
});