【发布时间】:2016-12-16 21:25:21
【问题描述】:
我正在使用以下代码在名为people_table 的表中添加一个新行:
$("#add_new_row").click(function() {
console.log("***");
$('table#people_table').append('<tr><td>Dima</td><td>Petrov</td><td>30</td><td><button type="button" class="btn btn-success" id="change_4">Change</button></td></tr>');
});
...
<button type="button" class="btn btn-primary" id="add_new_row">Add new row</button>
<table class="table table-hover" id="people_table">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th>Modify</th>
</tr>
{% for person in people %}
<tr>
<td>{{ person[1] }}</td>
<td>{{ person[2] }}</td>
<td>{{ person[3] }}</td>
<td><button type="button" class="btn btn-success" id="change_{{ person[0] }}">Change</button></td>
</tr>
{% endfor%}
</table>
但是在添加行之后是下面的函数
$("button[id^='change_']").click(function() {
console.log("+++");
});
对新添加的行中的按钮不起作用,但对其他按钮有效。有什么问题?
【问题讨论】:
-
它不起作用,因为代码在您将按钮添加到页面之前运行。您要么需要直接绑定事件,要么使用事件委托。
-
您应该使用 .on() 函数而不是 .click() 因为 .click() 不适用于动态元素。
标签: javascript jquery twitter-bootstrap frontend