将html插入dom后,.on(单击)不起作用

时间:2016-07-29 18:35:32

标签: jquery dom onclick

操作dom之后,点击事件不起作用我怎么能解决这个问题,我想要实现一个喜欢和不喜欢的动作,如果点击的话就像样式上的facebook一样按钮。

HTML

<button type="button" id="style-like-{{$style->id}}" class="wider-button pb-skeleton-button-transparent pb-skeleton-button-tq-blue"><i class="fa fa-heart"></i> Like</button>

JQUERY

/* like style */

styleId = $('#style-id').val();

styleLike = $('#style-like-' + styleId);
styleLikeUpdated = $('#style-like-updated-' + styleId);
// styleLike.click(function(){
styleLike.on('click', styleLikeUpdated, function() {

  styleId = $('#style-id').val();
  styleIdAjax = $('#style-id-ajax').val();
  userId = $('#user-id').val();
  like = 1;

  $.ajax({
    url: "style@like@processing",
    type: 'POST',
    data: {'like' : like, 'user' : userId, 'styleId' : styleIdAjax},
    headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
context: document.body
  }).done(function(response) {

styleId = $('#style-id').val();

swal("Liked", "Wow you really like this style.", "success");
styleLikeButton = $('#style-like-' + styleId);
styleLikeButton.detach();

console.log(styleLikeButton);

hrBeforeLikeButton = $('#before-like-button');
hrBeforeLikeButton.after(response.dislikeButton);

likeLabel = $('#like-label');
likeLabel.html(response.likeLabel);
  });

});

/* /end like style */

/* dislike style  */

styleId = $('#style-id').val();

styleDislike = $('#style-dislike-' + styleId);
        styleDislikeUpdated = $('#style-dislike-updated-' + styleId);
// styleDislike.click(function(){
    styleDislike.on('click',styleDislikeUpdated, function() {

  styleId = $('#style-id').val();
  styleIdAjax = $('#style-id-ajax').val();
  userId = $('#user-id').val();
  dislike = 0;

  $.ajax({
    url: "style@dislike@processing",
    type: 'POST',
        data: {'dislike' : dislike, 'user' : userId, 'styleId' : styleIdAjax},
    headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') },
context: document.body
  }).done(function(response) {

    styleId = $('#style-id').val();

styleDislikeButton = $('#style-dislike-' + styleId);
styleDislikeButton.detach();

hrBeforeLikeButton = $('#before-like-button');
hrBeforeLikeButton.after(response.likeButton);

likeLabel = $('#like-label');
likeLabel.html(response.likeLabel);
  });

});

/* /end dislike style */

0 个答案:

没有答案