簡體   English   中英

將click事件和參數綁定到div?

[英]Bind click event and argument to div?

因此,我確定這是一個非常簡單的解決方案,但是由於某種原因,我無法獲得有效的解決方案。

我有一個克隆的div,需要向其中添加click事件。 我嘗試綁定到每個克隆的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 ,並需要使用舊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然后單擊它,則可以正常工作。 它做的一切很棒。 當我連續克隆多個div然后嘗試單擊它們時,就會出現問題,它們都綁定有相同的songId參數,而不是每個都有自己的參數。

有任何想法嗎?

而是首先使用屬性將名為data-songid的songID保存到元素,因為在HTML中,您可以為元素分配一個ID,這樣您就可以克隆元素並輕松放入視圖中,希望這對您有所幫助,讓我知道你是否還不清楚。

有關數據屬性的更多參考,您將在此處獲得API

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM