Iterating through table cells using jquery

前端 未结 2 735
长发绾君心
长发绾君心 2021-02-13 20:25

I have a table containing a variable number of columns. I wrote a function to iterate through each cell in each row to do the following:

  1. Check for the presence of
2条回答
  •  孤独总比滥情好
    2021-02-13 21:15

    Here is how I would modify you code:

    • #MarketsTable td:has(:input): this selector will find TD that has at leats one INPUT element inside

    • no need to store your parts of html in variables IMO, just create the element when needed and append it to the TD

    Here's the modified code:

    function addPieCharts() {
    
        var colors = ["red", "blue"];
    
        // directly select the TD with an INPUT element inside
        $('#MarketsTable td:has(:input)').each(function() {
    
            var value = $(this).find(":input").val();
    
            if (value > 0) {
    
                // only make the values string if necessary, when value > 0
                var valStr = (100 - value).toString() + ', ' + value;
    
                // create your span tag and append it to 'this' (the TD in this case)
                $('').appendTo(this);
            }
    
        });
    
        $('.inlinesparkline').sparkline('html', {
            type: 'pie',
            sliceColors: colors
        });
    }
    

    DEMO

提交回复
热议问题