2016-01-30 85 views
2

我正在製作一個小型的個人應用程序,用jQuery創建html表格。我有這個腳本(我從這裏的某個地方借用並調整了一下),只需點擊一下按鈕,在我的表格末尾添加一個新列。jQuery腳本運行不正確

function addJSONKey(){ 
var first = true; 

$('#jsonTable').find('tr').each(function(){ 
    $(this).find('th').eq(-1).after(
     '<th contentEditable>New Key</th>' 
    ); 
     if(first === true){ 
      first = false;  
      // the function does not execute this statement 
      // even though the debugger breaks here. 
      $(this).find('td').eq(-1).after(
       '<td>Frist</td>' 
      ); 
     } else {     
      $(this).find('td').eq(-1).after(
       '<td contentEditable>Not First</td>' 
      ); 
     } 
}); 
} 

我想什麼腳本做的是,第一行是比其他人不同,但如果我運行該腳本,它無處不在,還給不是第一排。

+0

如果您不想爲其他行「不是第一個」,那麼您可以簡單地刪除您的其他部分 –

回答

1

你過度複雜一點。你可以通過它們的索引區分行並追加相應的新日或TD:

function addJSONKey() { 
 
    $('#jsonTable').find('tr').each(function(i) { 
 
    \t // Header row 
 
     if (i === 0) { 
 
      $(this).find('th').eq(-1).after('<th contentEditable>New Key</th>'); \t 
 
     } 
 
     // First data row 
 
     else if (i === 1) { 
 
      $(this).append('<td>Frist</td>'); 
 
     } 
 
     // Not header and not the first row 
 
     else { 
 
      $(this).append('<td contentEditable>Not First</td>'); 
 
     } 
 
    }); 
 
} 
 

 
$('button').click(addJSONKey);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button>Add</button> 
 

 
<table id="jsonTable"> 
 
    <tr> 
 
     <th>One</th> 
 
    </tr> 
 
    <tr> 
 
     <td>Data</td> 
 
    </tr> 
 
    <tr> 
 
     <td>Data</td> 
 
    </tr> 
 
</table>

0

function addJSONKey() 
{ 

    $('#jsonTable').find('tr').each(function(){ 
     $(this).find('th').eq(-1).after(
     '<th contentEditable>New Key</th>' 
    ); 
    }); 
    $('#jsonTable').find('tr').each(function(){ 
     if($(this).find('td').length == 0) 
     { 
      $(this).append('<td>Frist</td>'); 
     } 
     else 
     {     
      $(this).append('<td contentEditable>Not First</td>'); 
     } 
    }); 
} 

基本上取代你的方法你的布爾第一隻對第一行的第一列如此。

0

在你的代碼計算第1行,這是標頭,如first,要添加到第1非標題行,即第2行,即索引1,因爲它是基於:)

function addJSONKey(){ 
 
$('#jsonTable').find('tr').each(function(row){ 
 
    $(this).find('th').eq(-1).after('<th contentEditable>New Key</th>'); 
 
     if(row == 1){ 
 
      // the function does not execute this statement 
 
      // even though the debugger breaks here. 
 
      $(this).find('td').eq(-1).after('<td>Frist</td>'); 
 
     } else {     
 
      $(this).find('td').eq(-1).after(
 
       '<td contentEditable>Not First</td>' 
 
      ); 
 
     } 
 
}); 
 
} 
 
//addJSONKey();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="jsonTable"> 
 
    <tr><th>a</th><th>b</th></tr> 
 
    <tr><td>10</td><td>11</td></tr> 
 
    <tr><td>20</td><td>21</td></tr> 
 
</table> 
 
<button onclick="addJSONKey()">go</button>