【发布时间】:2016-10-11 01:54:22
【问题描述】:
通过从 ajax 成功事件接收到的 JSON 数据,我使用这些数据来制作动态 html 内容,类似于这样
function loop_json(data) {
var response_data = jQuery.parseJSON(data);
var vip_userId = $('#userId').val();
$(response_data.vip_poll).each(function(index, value) {
var t= '';
t += '<li class="vip-polls-holder" id="'+value.id+'">';
t += '<div class="user-img">';
t += '<a href="users.php?user_name='+response_data.vip_pollOwners[index].user_name+'"><img src="'+response_data.vip_pollOwners[index].user_avatar+'" class="user-img-pic img-circle" /></a>';
t += '</div>';
...
t +='</li>';
$('.vip-polls-holder-ul-mainDIV').append(t);
// And so I attach some functions with these li boxes such as
function1();
function2(); //and
VIP_dNd_multiple();
});
}
VIP_dNd_multiple() 在哪里->
function VIP_dNd_multiple() {
// let it be called part a
$trashVIP.each(function() {
$(this).droppable({
accept: "#VIPgalleryMulitple"+$(this).attr('id')+" > li",
activeClass: "ui-state-highlight",
drop: function (event, ui) {
console.log('abc'); //This prints one time
}
});
});
// let it be called part b
$("ul.VIPgalleryMulitple > li").each(function() {
var $item = $(this);
$item.click(function (event) {
event.preventDefault();
console.log('ok'); //This prints multiple times
});
});
}
问题是 VIP_dNd_multiple() 被调用的次数与 DOM 上存在的 li 元素一样多,因此控制台多次给出“ok”(函数的 b 部分)作为输出,这当然是不可取的。我不明白当我在 $(this) li 上使用 click 事件时,为什么所有 li 元素都在触发 console.log 操作?
令人惊讶的是,同一函数的 a 部分只正确输出了一次控制台。
【问题讨论】: