Iterating through table cells using jquery

前端 未结 2 736
长发绾君心
长发绾君心 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

    When you select td pass the context as tr(this) so that it will look for td only in the current tr. Try this.

    $("#MarketsTable tr").each(function () {
    
        $('td', this).each(function () {
            var value = $(this).find(":input").val();
            var values = 100 - value + ', ' + value;
    
            if (value > 0) {
                $(this).append(htmlPre + values + htmlPost);
            }
         })
    
    })
    
    0 讨论(0)
  • 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)
                $('<span class="inlinesparkline" values="' + valStr + '"></span>').appendTo(this);
            }
    
        });
    
        $('.inlinesparkline').sparkline('html', {
            type: 'pie',
            sliceColors: colors
        });
    }
    

    DEMO

    0 讨论(0)
提交回复
热议问题