This question already has answers here:
Event binding on dynamically created elements?
(23个答案)
2年前关闭。
我在我的网站上有这样的列表:
当我使用以下功能将新元素添加到此列表中时:
已正确添加,但无法通过以下方式点击:
所有其他元素都是可单击的。刷新网站后,新元素可以单击。如何使其工作而不刷新?
事件侦听器在
(23个答案)
2年前关闭。
我在我的网站上有这样的列表:
<ul id="listProfiles" class="list-group">
@foreach($profiles as $profile)
<li class="list-group-item" profileId="{{ $profile['id'] }}">{{ $profile['name'] }}</li>
@endforeach
</ul>
<div id="profileResult"></div>
当我使用以下功能将新元素添加到此列表中时:
$("#addNewProfileButton").on("click", function () {
profileName = $("#newProfileInput").val();
$("#newProfileInput").val('');
$.ajax({
method: 'GET',
data: {
profileName: profileName
},
url: '/addNewProfiles'
}).success(function (newProfile) {
console.log(newProfile);
$("#listProfiles li:last").after('<li class="list-group-item" profileId="' + newProfile.id + '">' + newProfile.name + '</li>');
}).error(function (msg) {
console.log(msg);
});
});
已正确添加,但无法通过以下方式点击:
$("#listProfiles li").click(function () {
profileId = $(this).attr('profileId');
$.ajax({
method: 'GET',
data: {
profileId: profileId
},
url: '/spiderProfileDetails'
}).success(function (msg) {
$('#profileResult').html(msg);
}).error(function (msg) {
console.log(msg);
});
});
所有其他元素都是可单击的。刷新网站后,新元素可以单击。如何使其工作而不刷新?
最佳答案
$("#listProfiles li").click()
在所选元素(即当时存在的元素)上添加事件侦听器。新元素不会受到此影响。
解决此问题的最佳方法是使用事件委托。您可以将其视为“动态事件监听”的形式:
$("#listProfiles").on("click", "li", handlerFunction);
事件侦听器在
listProfiles
元素上注册,但是仅当事件起源于某个元素,且该元素与作为第二个参数传递给on()
方法的选择器匹配时,才调用处理程序函数。这样,它将包括以后添加的元素。关于javascript - jQuery,新元素不可点击,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45547605/
10-09 00:44