简体   繁体   English

将click事件和参数绑定到div?

[英]Bind click event and argument to div?

So i'm sure this is a pretty easy solution but for some reason I can't get a solution that works. 因此,我确定这是一个非常简单的解决方案,但是由于某种原因,我无法获得有效的解决方案。

I have a cloned div that I need to add a click event to. 我有一个克隆的div,需要向其中添加click事件。 The function that I am trying to bind to each cloned div is the following: 我尝试绑定到每个克隆的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)
            }
        });
    })
  })
}

My problem occurs when cloning the div. 克隆div时发生我的问题。 During the clone I am resseting the id to a new one and need to use the old id as the argument for the allowLike(songId) function. 在克隆期间,我将id重置为一个新id ,并需要使用旧id作为allowLike(songId)函数的参数。

What I've done to try and get that id is below: 我为获得该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

Now, this works fine and dandy if I clone the div and then click on it. 现在,如果我克隆div然后单击它,则可以正常工作。 It does everything great. 它做的一切很棒。 The problem occurs when I clone multiple divs in a row and then try and click on them, they are all bound with the same songId argument instead of each having their own. 当我连续克隆多个div然后尝试单击它们时,就会出现问题,它们都绑定有相同的songId参数,而不是每个都有自己的参数。

Any ideas? 有任何想法吗?

Rather first of all use an attribute to save songID named data-songid to the element, as in HTML you can have single id assigned to the element, this way you can just clone the element and put in the view easily, hope this helps, let me know if you are still not clear. 而是首先使用属性将名为data-songid的songID保存到元素,因为在HTML中,您可以为元素分配一个ID,这样您就可以克隆元素并轻松放入视图中,希望这对您有所帮助,让我知道你是否还不清楚。

More reference about data attributes and here you get API 有关数据属性的更多参考,您将在此处获得API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM