gpt4 book ai didi

javascript - 如何向在运行时创建的元素添加事件?

转载 作者:行者123 更新时间:2023-11-30 12:36:32 25 4
gpt4 key购买 nike

在下面的代码中,添加 按钮动态附加 <TR> ,其中包含一个删除按钮,到一个表。以下代码$('a.remove_performer').live()得到“Uncaught TypeError: undefined is not a function”的错误,无法附加事件处理程序?

更新:更改了 live()on()错误消失了。但是,事件处理程序仍未附加。

http://jsfiddle.net/emg9yxwc/1/

<table>
<thead>
<tr>
<th>Column1</th>
<th></th>
</tr>
</thead>
<tbody id="performerBody"></tbody>
<tfoot>
<tr>
<td>
<select id="performerList" name="performerList" class="valid">
<option value="1">performer1</option>
<option value="2">performer2</option>
</select>
</td>
<td><a id="addNewPerformer" href="#" class="add_performer">Add</a>

</td>
</tr>
</tfoot>
</table>

<script>
$(document).ready(function () {
// Add new row
$("#addNewPerformer").click(function (e) {
e.preventDefault();
$last = $("#performerBody tr:last");
var index = 0;
if ($last.length > 0) {
index = $last.find(':input:first').attr('name').match(/\d+/);
index = parseInt(index) + 1;
}
var selected = $("#performerList").val();
if ($('#performerBody input[value="' + selected + '"]').length === 0) {
var name = "Performers[" + index + "].Id";
var selectedText = $("#performerList :selected").text();
$("#performerBody").append('<tr><td><span style="display:none"><input name="' + name + '" type="number" value="' + selected + '"></span>' + selectedText + '</td><td><a href="#" class="remove_performer">Remove</a></td></tr>');
}
});

// Remove
$('a.remove_performer').on("click", function (e) { // was live
e.preventDefault();
$(this).parent().parent().remove();
});
});
</script>

最佳答案

.live()1.7 中弃用并在 1.9

中移除

事件处理程序只绑定(bind)到当前选中的元素;在您的代码进行事件绑定(bind)调用时,它们必须存在于页面上。

您需要使用 Event Delegation使用 .on()委托(delegate)事件方法。

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached.

$(document).on('event','selector',callback_function)

代替 document 你应该使用最近的静态容器。

根据您的代码。使用

$("#performerBody").on('click', 'a.remove_performer', function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});

关于javascript - 如何向在运行时创建的元素添加事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25905232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com