我有一个 jQuery 函数,它在 ASP.Net 中执行简单的 Ajax GET,并使用它返回的数据(Json 数组)填充网页。
我正在尝试将点击事件绑定(bind)到使用下面的 lopp 创建的每个 div,但是当它运行时,所有点击事件都会在页面加载时同时发生!
有什么想法吗?
function grabList() {
$('#temp').empty();
$.ajax({
url: '/Home/GoModel',
method: 'GET',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$('#temp').append('<div class="host col-sm-3"> id=' + data[i].name + '>' + data[i].name + '</div>');
if (data[i].hostConnected === true) {
$('#temp').append('<div class="host connected col-sm-3" id=' + data[i].name + '>' + data[i].name + '</div>');
continue;
}
$('#' + data[i].name).on('click', connect(data[i].name)); // Problem occurs
}
$('#container').html($('#temp').html());
}
});
}
最佳答案
你可以试试:
function grabList() {
$('#temp').empty();
$.ajax({
url: 'https://api.github.com/repositories?since=700',
method: 'GET',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$('#temp').append('<div class="host col-sm-3" id=' + data[i].name + '>' + data[i].name + '</div>');
if (data[i].hostConnected === true) {
$('#temp').append('<div class="host connected col-sm-3" id=' + data[i].name + '>' + data[i].name + '</div>');
continue;
}
(function (ele) {
$('#' + ele).on('click', function (e) {
alert(ele);
});
})(data[i].name);
}
$('#container').html($('#temp').html());
}
});
}
$(function () {
grabList();
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="temp"></div>
<div id="container"></div>
关于javascript - 在循环 "auto"内添加 jQuery 点击事件点击所有事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38772479/