所以我相信這是一個非常簡單的解決方案,但由於某種原因,我無法獲得可行的解決方案。將點擊事件和參數綁定到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 –