[英]Calling a click event of a dynamically created element
I'm pretty new to all things javascript related, and I seem to have got myself in a pickle. 我对与javascript相关的所有事物都相当陌生,而且似乎让自己陷入了困境。 I'm creating a site which displays a seating plan of an office. 我正在创建一个显示办公室座位计划的站点。 When the page loads, I load data retrieved from the database, into a function that loops through it and creates an anchor for each person. 页面加载时,我将从数据库中检索的数据加载到一个循环访问该函数并为每个人创建锚点的函数中。
This is my method: 这是我的方法:
function getDesks(coordsArr) {
for (var i = 0; i < coordsArr.length; i++) {
var element = $("<a href='' class='deskBtn' data-name='" + coordsArr[i].UserName + "'>.</a>");
$(element).css({
"top": coordsArr[i].DeskYCoord,
"left": coordsArr[i].DeskXCoord
}).appendTo(".map");
}
}
The problem i'm having is where to place the following ajax click event. 我遇到的问题是在哪里放置以下ajax click事件。
$('.deskBtn').on('click', function () {
var user = $(this).attr("data-name");
console.log(user);
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: {user: user},
success: function (data) {
}
});
});
I tried placing it after the for loop, but when I click one of the anchor tags the data gets logged to the screen, however, it quickly vanishes. 我尝试将其放置在for循环之后,但是当我单击其中一个锚标记时,数据就会记录到屏幕上,但是很快就消失了。 Any suggestions would be great. 任何建议都很好。
为什么不能只在for循环中添加处理程序?
$(element).on('click', function() { ... })
Delegate the event to a static element. 将事件委托给静态元素。 Do it for body
: 为body
:
$('body').on('click', '.deskBtn', function () {
var user = $(this).attr("data-name");
console.log(user);
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: {user: user},
success: function (data) {
}
});
});
You should try with a live 你应该尝试一下
$(document).ready(function(){
$('.deskBtn').live('click', function(){
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.