Pregunta

I'm trying to collect values for Chart.js that takes this array

data = [{ value:1, color:#123456 }]

HTML:

<table class="card">
    <tr class="section1">
        <td class="label">One</td>
        <td class="goal">1</td>
    </tr>
    <tr class="section2">
        <td class="label">Two</td>
        <td class="goal">2</td>
    </tr>
    <tr class="section3">
        <td class="label">Three</td>
        <td class="goal">3</td>
    </tr>
    <tr class="section4">
        <td class="label">Four</td>
        <td class="goal">4</td>
    </tr>
    <tr class="section5">
        <td class="label">Five</td>
        <td class="goal">5</td>
    </tr>
    <tr class="section6">
        <td class="label">Six</td>
        <td class="goal">6</td>
    </tr>
</table>

CSS:

table.card tr.section1 td.label{
    color: #c26558;
}
table.card tr.section2 td.label{
    color: #cdaf76;
}
table.card tr.section3 td.label{
    color: #6e9874;
}
table.card tr.section4 td.label{
    color: #809ead;
}
table.card tr.section5 td.label{
    color: #467082;
}
table.card tr.section6 td.label{
    color: #ac9578;
}

JAVASCRIPT:

var data = []; //{ value: 30, color:"#F38630" },
var goals = document.getElementsByTagName( $('table.card .goal').html() );
var quantities = jQuery.makeArray( goals );

for( var i=0; i<quantities.length; i++ ){
    var labelColor = '#000000';

    $('table.card .goal').each(function(){
        if( $(this).html() == quantities[i] ){
            labelColor = rgb2hex( $(this).closest('tr').find('.label').css('color') );
        }
    });

    data[i] = { 'value':quantities[i], 'color':labelColor };
}

This is my latest attempt at making an array of quantities to work with. I was fiddling with jQuery.toArray() before makeArray(). I don't know, maybe my entire approach is off. The chunk that grabs the css('color') is working, I'm pretty happy with that, but I am having a hard time turning the values of the .goal cells into an array.

Here's the Chart.js documentation: http://www.chartjs.org/docs/

¿Fue útil?

Solución

I think you've made it much more complicated than need be. Just select the td.goal elements, and use .map() to return an object to a new array with the values from the current goal.

var result = $("table.card tr[class^=section] td.goal").map(function(i, tr) {
    var goal = $(this);
    return {
        value: parseInt(goal.text(), 10),
        color:goal.prev().css('color') || '#000000'
    };
}).toArray();

Otros consejos

Use .map()

Fiddle Demo

var data = $('.card tr').map(function () {
    $this = $(this);
    return {
        value: $this.find('.goal').text(),
        color: $this.find('.label').css('color') //will return like "rgb(194, 101, 88)"
    }
}).get();
console.log(data);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top