2013-05-14 59 views
0

我有一個非常好的功能,即模仿「長按」與jQuery的創建工作DOM腳本修改對象

(function($) { 
    $.fn.longClick = function(callback, timeout) { 
     var timer; 
     timeout = timeout || 500; 
     $(this).mousedown(function() { 
      timer = setTimeout(function() { callback(); }, timeout); 
      return false; 
     }); 
     $(document).mouseup(function() { 
      clearTimeout(timer); 
      return false; 
     }); 
    }; 

})(jQuery); 

$('#button').longClick(function(){ /* everything I want */ }) 

此代碼工作正常與媒體鏈接存在的項目。
但是,如果我通過jQuery將此按鈕添加到DOM, - 此腳本不起作用。
這種結構也不會longClick工作,但工作與「點擊」正確:

$(document).on('longClick', "#button",function() { 
     /* everything I want */ 
    }); 

我該如何解決呢?

謝謝!

===========
UPD

這裏是另一個代碼,與原來的元素能正常工作,但不與jQuery的添加工作,但它使用的默認方法。

var pressTimer;  
$("#button").mouseup(function(){ 
    clearTimeout(pressTimer) 
    return false; 
}).mousedown(function(){ 
    pressTimer = window.setTimeout(function() { 
     /* function */ 
    },500) 
    return false; 
}); 
+1

您需要將事件系統在jQuery的擴展,而不是增加一個插件的方法。 '$ .fn.longClick'不會創建一個名爲'「longclick」'的事件,它只是在jQuery對象上創建一個方法。 – Esailija 2013-05-14 10:21:36

+0

我用原始的jQuery方法添加了另一個代碼,可能會給你一個想法如何解決它。謝謝。 – 2013-05-14 18:17:18

+0

你需要擴展事件系統,閱讀並理解所有這些http://learn.jquery.com/events/event-extensions/ – Esailija 2013-05-14 19:41:56

回答

0

好的代碼:

var pressTimer 
$(document).on("mouseup", "#button", function(){ 
     clearTimeout(pressTimer) 
    // Clear timeout 
    return false; 
}) 
$(document).on("mousedown", "#button", function(){ 
     // Set timeout 
    pressTimer = window.setTimeout(function() { 
     /* MY SUPER FUNCTION */ 
    },500) 
    return false; 
} ) 
0

爲了使不上呈現的物品(如那些最初未加入DOM而是通過的jQuery或其他一些方法,而加的)一些代碼工作,你必須使用的http://api.jquery.com/delegate/(.delegate())函數jQuery的。因此,而不是這樣做的:

$('#button').on('longClick', "#button",function() { ... 

你需要做的

$(document).delegate('#button', 'longclick', function() {... 

希望它能幫助!

編輯1: 試試這樣說:

$(document).delegate('#button', 'mousedown', function(){ 
    clearTimeout(pressTimer) 
    return false; 
}); 
$(document).delegate('#button', 'mouseup', function(){ 
    pressTimer = window.setTimeout(function() { /* function */ },500); 
    return false; 
}); 
+0

不,代碼不工作=( – 2013-05-14 18:16:21

+0

好委託是要走的路,只是讓相信你已經有了一個正確的代碼,其餘 – 2013-05-15 10:32:08

+0

嘗試使用 VAR pressTimer; 的$(document).delegate( '#鍵', '鼠標按下',函數(){ clearTimeout(pressTimer) 返回false; }); $(文件).delegate( '#按鈕', '鼠標鬆開',函數(){ pressTimer = window.setTimeout(函數(){ /*函數* /} ,500) 返回false ; }); – 2013-05-15 10:34:47