长按动态内容的jQuery插件

时间:2014-09-27 09:20:08

标签: javascript jquery ajax dynamic-content

我已经编写了一个插件来为我的Web应用程序创建长按事件处理程序。我知道它不是太先进而且它的功能很低,但我正在努力改进它。你可以在下面看到我的插件:

$(function($) {
  var holdTimer;
  var timerRunning = false;
  $.fn.longClick = function(handler, time) {
    if (time == undefined) time = 500;
    return this.on({
      mouseup: function() {
        clearTimeout(holdTimer);
        timerRunning = false;
      },
      mousedown: function() {
        var self = this;
        timerRunning = true;
        holdTimer = window.setTimeout(function() {
          handler.call(self)
        }, time);
      }
    })
  };
  $.fn.longClick.defaultTime = 500;
}(jQuery));

我的问题是什么?

我处于将Ajax生成的内容放在我的页面上的情况,您可以很容易地知道.longClick()不再为这些元素工作。

我有以下代码段:

$.ajax({
  url: "/ajax/",
  type: "POST", 
  data: {
    action: "load-posts",
  },
  dataType: "html",
  success: function(data) {
    $(".profile-wrapper").append(data);
  }
});

data看起来像这样:

<div class="post">
  <div class="comments">Comments</div>
</div>

然后我需要为.longClick使用.comments事件。我发现这个,在Stack Overflow上,我知道我的情况是什么,但我不知道如何修改我的插件以像$(selector).on(event,childSelector,data,function)一样工作。

您如何修改此插件以处理动态内容?感谢您的耐心和帮助。

编辑@AminJafari

现在会触发长按事件,但在函数内部,.post似乎是undefined

$(".profile-wrapper .tabs-wrapper .tab .post").longClick(function () {
  var $post = $(this);
  var menuTop = $post.offset().top + "px";
  // ...
}

来自控制台的输出:

Uncaught TypeError: Cannot read property 'top' of undefined 

1 个答案:

答案 0 :(得分:1)

<强>更新:

$(function($) {
  var holdTimer;
  var timerRunning = false;
  $.fn.longClick = function(handler, time) {
    if (time == undefined) time = 500;
    var that=$(this);
    $(document).on('mouseup',that,function(){
        clearTimeout(holdTimer);
        timerRunning = false;
      });
    $(document).on('mousedown',that,function(){
        var self = this;
        timerRunning = true;
        holdTimer = window.setTimeout(function() {
          handler.call(self)
        }, time);
     });
  };
  $.fn.longClick.defaultTime = 500;
}(jQuery));