且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Javascript中解析HTML的***方法

更新时间:2023-02-09 15:25:15

您可以使用 jQuery 轻松遍历DOM并自动创建具有该结构的对象。

You can use jQuery to easily traverse the DOM and create an object with the structure automatically.

var $dom = $('<html>').html(the_html_string_variable_goes_here);
var featureInfo = {};

$('table:has(.dataLayer)', $dom).each(function(){
    var $tbl = $(this);
    var section = $tbl.find('.dataLayer').text();
    var obj = [];
    var $structure = $tbl.find('.dataHeaders');
    var structure = $structure.find('th').map(function(){return $(this).text().toLowerCase();});
    var $datarows= $structure.nextAll('tr');
    $datarows.each(function(i){
        obj[i] = {};
        $(this).find('td').each(function(index,element){
            obj[i][structure[index]] = $(element).text();
        });
    });
    featureInfo[section] = obj;
});

工作演示

代码可以使用内部具有不同结构的多个表。 。还有每个表中的多个数据行..

The code can work with multiple tables with different structures inside.. and also multiple data rows inside each table..

featureInfo将保存最终的结构和数据,并且可以像

The featureInfo will hold the final structure and data, and can be accessed like

alert( featureInfo['*** Villages'][0]['English Translation'] );

alert( featureInfo['*** Villages'][0].id );