我正在动态地添加一排,我需要在它之后做2件事:
-
清除值
-
单击新创建的链接(该链接在一个单元格中)。
这是将行添加到表中的代码(正常工作):
var row = $('.records_table tbody>tr:last').clone(true);
row.insertAfter('.records_table tbody>tr:last');
我的行HTML代码看起来像这样:
<tr class="odd">
<td class="name">name_0</td>
<td class="type">type_0</td>
<td class="value">value_0</td>
<td class="edit">
<a href="edit" class="edit">edit</a>
</td>
</tr>
所以,我的第一个问题:如何清除值name_0,type_0和value_0?
现在,第二个问题。我需要模拟单击链接"编辑",以触发链接到选择器" A.Edit"的事件(此事件是正确触发的,该事件是针对其他加载的行中的其他行中预先存在的编辑链接触发的页)。我可以将按钮作为var editbtn = $("td:last", row)
。我可以隐藏执行editbtn.hide()
的链接,但是执行editbtn.click()
并未按预期触发事件。
应该单击的处理程序是:$(document).on('click', 'a.edit', function(e) {
,它再次在其他行中使用其他链接。
有什么想法?
您可以像这样穿越它
var row = $('.records_table tbody>tr:last').clone(true);
row.insertAfter('.records_table tbody>tr:last');
$('.records_table tbody>tr:last') // gets last tr
.find('td') // gets all td
.not('.edit') // not the td with class=edit
.text('') // make all text empty
.end() // go back to first selector
.find('a.edit').click(); // find anchor within tr and trigger click
http://jsfiddle.net/59hyl/1/
如果要单击最后一个TD而不是锚。。您可以像这样做
$('button').click(function() {
var row = $('.records_table tbody>tr:last').clone(true);
row.insertAfter('.records_table tbody>tr:last');
$('.records_table tbody>tr:last')
.find('td')
.not('.edit')
.text('');
$('tbody td:last').click();
});
$('.records_table').on('click', 'td.edit', function(e) {
e.preventDefault();
console.log("anchor number " + $('td.edit').index(this) + 'clicked');
});
http://jsfiddle.net/hep5q/
我相信这将回答您的两个问题:
html:
<button id="btn">Add row</button>
<table class="records_table">
<thead><tr><th>Head</th></tr></thead>
<tbody><tr><td>*</td></tr></tbody>
</table>
javaScript:
//simple function to repeat a string num times
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
var i = 2;
var char = '*';
var lastRowSelector = '.records_table tbody tr:last';
//click handler for the cell
$(lastRowSelector + ' td').click(function() {
alert($(this).text());
});
$('#btn').click(function(){
var lastRow = $(lastRowSelector);
//clone the row (note that handler will be cloned as well)
var newRow = lastRow.clone(true);
//obtain the only 'td' cell in the row
var cell = newRow.find('td');
//clear text of the cell by replacing it with new text. You could call cell.text('') to just clear it
cell.text(char.repeat(i++));
//insert the row to the end of the table
newRow.insertAfter(lastRowSelector);
//simulate click
newRow.click();
});
http://jsfiddle.net/pr5jr/1/
您可以使用:last
var row = $('.records_table tbody>tr:last').clone(true);
row.insertAfter('.records_table tbody>tr:last');
// Recently added row..
var recentRow = $('.records_table tbody>tr:last');
recentRow.find('td').each(function(){
$(this).text(''); // Will clear the values..
})