2017-03-05 80 views
2

我想將我的表格轉換爲html。我試圖獲得來自input text fields的數據,而不是從input checkbox fields 以下是我的javascript代碼可以在fiddle可以看出:區分jquery選擇器中的文本和複選框

$(document).ready(function(){ 
$('#hello').click(function(e) {  
var array = []; 
var headers = []; 
$('#my_table tr:first-child td').each(function(index, item) { 
    headers[index] = $('> input[type="text"]', item).val(); 
}); 
$.each(headers, function(index, item) { 
     var name=item; 
    var data =[]; 
    $('#my_table tr:first-child').nextAll().each(function() { 
     $('td:nth-child('+(index+1)+')', $(this)).each(function(index, item) { 
      data.push(parseInt($('> input[type="text"]', item).val())); 
     }); 
     }); 
    array.push({name: name, data:data}); 
    }); 
    var categories=array[0].data; 
    alert(categories); 
    array.shift(); 
       var chart= new Highcharts.Chart({ chart: { 
     renderTo: 'container' 
    }, 
      title: { 
       text: 'Monthly Average Temperature', 
       x: -20 //center 
      }, 
      subtitle: { 
       text: 'Source: WorldClimate.com', 
       x: -20 
      }, 
      xAxis: { 
       categories: categories 
      }, 
      yAxis: { 
       title: { 
        text: 'Temperature (°C)' 
       }, 
       plotLines: [{ 
        value: 0, 
        width: 1, 
        color: '#808080' 
       }] 
      }, 
      legend: { 
       layout: 'vertical', 
       align: 'right', 
       verticalAlign: 'middle', 
       borderWidth: 0 
      }, 
      series: array 
     }); 
     }); 
     }); 

我的代碼應該拿第一列作爲x軸。爲此,它應該跳過複選框列。但是,jquery選擇器似乎不能區分兩種類型的輸入並跳過列類型。我應該採取什麼不同的方式來實現我的目標?

回答

1

這有兩個主要原因:

  • 在你建立你不篩選出的第一列標頭中的循環。確實,input[type="text"]選擇器不會給出第一列的結果,但它仍會在headers陣列中生成一個條目。相反,移動是input選擇進入主選擇,讓你甚至不訪問第一列

  • 在你構建array變量的循環,您可以通過選擇td:nth-child('+(index+1)+')'訪問td,但自從index值從0開始,您將訪問仍然是第一列的子數字1。所以你需要在那裏寫index+2

與一些其它的改進(利用的map是用於產生陣列有用),下面的代碼可以使用:

var headers = $('#my_table tr:first-child input[type="text"]').map(function() { 
     return $(this).val(); 
    }).get(); 
    var array = $.map(headers, function(item, index) { 
     var name = item; 
     var data = $('#my_table tr td:nth-child('+(index+2)+') input[type="text"]') 
      // slice(1) will skip the first row (alternative to your method) 
      .slice(1).map(function() { 
       return +($(this).val()); // unitary + will do number conversion 
      }).get(); 
     return {name: name, data: data}; 
    }); 
    var categories = array.shift().data; 
    var chart= new Highcharts.Chart({ chart: { 
     // ... etc. 

this updated jsfiddle輸入一些輸入之後,我得到這個結果:

enter image description here

+0

謝謝。如果我使用索引+ 2,標題會搞砸 –

+0

也許你可以解釋你想要什麼樣的輸入和輸出圖像。我添加了用於測試我提供的解決方案的輸入/輸出屏幕截圖。你能澄清嗎? – trincot