我想在单击“提醒”按钮时将div添加到表中,并且div应该在类" name2"之后插入,但是当我单击按钮时,原始文本消失了,并且测试()函数无法工作,如何解决?
function test() {
alert('test')
}
$('#form').on('click', '.test', function () {
var $row = $(this).closest('tr');
$('.one',$row).each(function() {
$(this).html($('<div class="name"></div>').text('Watson')).inserAfter('.name2');
});
test();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="form">
<tr>
<th>Name Table</th>
</tr>
<tr>
<td class="one">
<div class="name1">Henry</div>
<div class="name2">Harry</div>
</td>
<td>
<div><button type="button" class="test">Alert</button></div>
</td>
</tr>
<tr>
<td class="one">
<div class="name1">Berry</div>
<div class="name2">Terry</div>
</td>
<td>
<div><button type="button" class="test">Alert</button></div>
</td>
</tr>
</tbody>
&#13;
答案 0 :(得分:2)
Trt使用append代替html
function test() {
alert('test')
}
$('#form').on('click', '.test', function () {
var $row = $(this).closest('tr');
$('.one',$row).each(function() {
$(this).append($('<div class="name"></div>').text('Watson')).inserAfter('.name2');
});
test();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="form">
<tr>
<th>Name Table</th>
</tr>
<tr>
<td class="one">
<div class="name1">Henry</div>
<div class="name2">Harry</div>
</td>
<td>
<div><button type="button" class="test">Alert</button></div>
</td>
</tr>
<tr>
<td class="one">
<div class="name1">Berry</div>
<div class="name2">Terry</div>
</td>
<td>
<div><button type="button" class="test">Alert</button></div>
</td>
</tr>
</tbody>
&#13;
答案 1 :(得分:0)
在您的情况下无需使用.each
,因此您可以直接使用
var $name2 = $(this).closest('tr').find('.name2');
您可以像这样使用 InsertAfter()
function test() {
alert('test')
}
$('#form').on('click', '.test', function () {
var $name2 = $(this).closest('tr').find('.name2');
($('<div class="name"></div>').text('Watson')).insertAfter($name2);
test();
});