2012-11-27 38 views
0

花了我好几天的时间才想出以下内容,现在我意识到它仍然无法正常工作。我的“添加行”按钮无法正常工作。我错过了什么?“添加行”逻辑无法按预期工作

<table> 
    <tr> 
     <th>field</th> 
     <th>comparison</th> 
     <th>value</th> 
    </tr> 
    <tr> 
     <td> 
      <select style="width:5em;" class="field"> 
       <option>name</option> 
       <option>age</option> 
       <option>sex</option> 
      </select> 
     </td> 
     <td> 
      <select style="width:5em;" class = "comp"> 
       <option>equals</option> 
       <option>starts with</option> 
       <option>not equal to</option> 
      </select> 
     </td> 
     <td><input type="text" class = 'value'></td> 
     <td><button id="add">Add row</button></td> 
    </tr> 
</table> 
$('#tableSearchMainAccount1 tr').each(function() { 
    var td = ''; 
    // used to skip table header (if there is) 
    if ($(this).find("td:first").length > 0) { 
     $(this).find('option:selected').each(function() { 
      td = td + $(this).text() + ','; 
     }); 
     td = td + $(this).find('input').val(); 
     filt[ctr] = td; 
     ctr += 1; 
    } 
}); 
//alert(filt); //alert output like name,equals,ann,age,equals,11 

$('#add').live('click', function() { 
    var $lastTr = $('table tr:last'); 
    console.log($lastTr); 
    $lastTr.clone().insertAfter($lastTr); 
    // Remove the button from the previous tr, otherwise each row will have it. 
    $('#add', $lastTr) 
     .replaceWith('<button class="remove_row">Remove row</button>'); 
}); 

$('.remove_row').live('click', function() { 
    $(this).closest('tr').remove(); 
}); 
+1

什么坏了?你期待什么样的行为,而你却看到了什么? – Sampson

+2

嗯,也许是因为你的HTML中没有任何id或类名?这是什么? - >#tableSearchMainAccount1 – pbibergal

+0

没有什么坏..它只是没有与我合作 –

回答

1

从讨论中的意见首发,看来你还没有引用jQuery的。

enter image description here

以下内容添加到您的<head></head>部分:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script> 

还有许多其他的CDN主机jQuery的你,或者你可以自己下载。所有这些细节都可以在http://jquery.com/download/上找到。

所以您的标记看起来像下面这样:

<!DOCTYPE html> 
<html> 
    <head> 
     <title>My jQuery Project</title> 
     <script src="jquery-1.8.3.min.js"></script> 
     <script src="scripts.js"></script> 
    </head> 
    <body> 
     <table>...</table> 
    </body> 
</html> 

请注意,我还引用所谓的“scripts.js中”另一个外部文件。这是您可以放置​​所有JavaScript和jQuery逻辑的地方。

$(document).ready(function(){ 
    /* Wrapping your code with a document-ready 
     block will ensure that the DOM will be 
     ready before your code runs 
    */ 
}); 
0

更换

<table> 

<table id="tableSearchMainAccount1"> 

将是我10