【问题标题】:Jquery: convert html to arrayJquery:将html转换为数组
【发布时间】:2012-03-28 10:21:20
【问题描述】:

有没有一种简单的方法可以使用 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'

谢谢!

【问题讨论】:

    标签: javascript jquery html arrays


    【解决方案1】:

    更新

    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);
    

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

    【讨论】:

    • 但是 html 是在一个字符串中。而且还不是一个现有的元素。
    • @Jaap:更新了,您也可以将“有效”的 htmlstring 包装到 jquery 构造函数中。
    【解决方案2】:

    这样的事情应该可以解决问题,但它不会递归地工作(仅适用于直接的身体孩子)。

    var tags = [];
    
    $('body').children().each( function( index, element ) {
        tags.push({ 
            'tag' : element.nodeName.toLowerCase(), 
            'value' : element.text()
        });
    });
    

    【讨论】:

    • 但是 html 是在一个字符串中。而且还不是一个现有的元素。
    • 只需将字符串传递给$()选择器,例如$('&lt;body&gt;&lt;h1&gt;text&lt;/h1&gt;&lt;/body&gt;').children()
    • @Jaap 使其成为一个 jquery 对象然后:$(htmlString) 并运行 scibuff 和 @jAndy 的代码。
    【解决方案3】:

    这里有一个想法

    $('body *').each(function(i){
    console.log($(this).text());
    console.log(this.nodeName);
    console.log(i);
    });
    

    【讨论】:

    • 注意:使用* 可能会很慢
    猜你喜欢
    • 2013-01-31
    • 2010-11-06
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多