所以我相信这是一个非常简单的解决方案,但由于某种原因,我无法获得可行的解决方案。将点击事件和参数绑定到div?
我有一个克隆的div,我需要添加一个单击事件。我试图绑定到每个克隆的div的功能如下:
function allowLike(songId){
$('.queueTrack').off('click').on('click', function(){
console.log('clicked like');
console.log(songId);
$.getJSON('/user', function(data){
var token = data.token;
songId = songId;
$.ajax({
url: 'https://api.soundcloud.com/me/favorites/' + songId + '?oauth_token=' + token,
type: 'PUT',
success: function(result) {
console.log('u liked' + songId)
}
});
})
})
}
克隆div时出现我的问题。在克隆过程中,我将id
转换为新的,并且需要使用旧的id
作为allowLike(songId)
函数的参数。
我做了什么,试图让该ID是下面:
var songId = this.id; //This is the id I need for the function
console.log(songId) // this logs correctly
var cloned = $(this).clone(); //cloning the div
cloned.attr("id", queueList.length - 1); //changing the div's id to a new one
$("<span class = 'soundHover'><div class='soundMove'><i class='moveUp fa fa-arrow-up'></i><i class='moveDown fa fa-arrow-down'></div></i><span class='deleteQueue'><i class='fa fa-times'></i></span></span>").prependTo(cloned); //add some stuff to the new cloned div
$(cloned).appendTo(".queueListDiv").addClass("animated flipInX, queueTrack").removeClass('track'); //add the cloned div to it's new location
allowLike(songId); //call the allowLike function to bind click event
现在,如果我克隆格,然后点击它,这个工作非常愉快。它做的一切都很棒。当我连续克隆多个div,然后尝试点击它们时,会出现问题,它们都以相同的songId
参数绑定,而不是每个都有自己的参数。
任何想法?
你应该用事件委托,用于处理动态元素,而不是添加处理程序,你做了 –
登录克隆的标识,看看这些都是一样的。我认为问题是与queueList.length –