jQuery - 从html构建对象

时间:2015-08-26 20:39:21

标签: javascript jquery html

我的最终目标是获取我的网站信息。我试图得到这样的东西:

{
    Goals: {
       1: 'ET6',
       2: 'ET10'
    },
    Sub-Off: 80,
    Sub-On: 'ET1'
}

所以我有以下标记(必须使用巨大的换行符):

<span class="stats jamie">

        <img src="/client/images/icon-ball.gif" alt="Goals" width="13" height="13">
        ET:6,ET:10

        <img src="/client/images/suboff.gif" alt="Sub-Off" width="13" height="13">
        80      

        <img src="/client/images/subon.gif" alt="Sub-On" width="13" height="13">
        ET:1

                                        </span>

到目前为止我有什么

$('.jamie').find('img').each(function(index){
    console.info($(this).attr('alt'));
});

1 个答案:

答案 0 :(得分:3)

var stats = {};

$('.jamie img').each(function(){
    var name = $(this).attr('alt');
    var data = $(this)[0].nextSibling       // Get the next node
                         .nodeValue         // Get its text value
                         .trim()            // Remove the extra spaces
                         .toLowerCase()     // to lower case
                         .replace(/:/g,'')  // remove colons
                         .split(',');       // split on commas
    stats[name] = data;                     // add to object
});

console.log(stats);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<span class="stats jamie">






        <img src="/client/images/icon-ball.gif" alt="Goals" width="13" height="13">
        ET:6,ET:10






















        <img src="/client/images/suboff.gif" alt="Sub-Off" width="13" height="13">
        80






















        <img src="/client/images/subon.gif" alt="Sub-On" width="13" height="13">
        ET:1











                                        </span>