簡體   English   中英

jQuery-如何在附加選擇器上鏈接事件

[英]jQuery - How to chain event on appended selectors

我試圖將代碼從此答案改編為jQuery附加元素,而不使用任何“標志”變量。

原始代碼是:

$(window).mousedown(function(e) {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
        alert('mousedown > 2 sec');   
    }, 2000); 
}).mouseup(function(e) {
    clearTimeout(this.downTimer); 
});​

所以我看不到如何在document使用它:

$(document).on('mousedown', '.item', function(){
// How to chain mouseup ? 
});

我嘗試過

$(document).find('.item')

但沒有運氣。

這不能使用鏈接來完成,因為.on()返回調用它的對象,並且不包括它委托給它的選擇器。

相反,您可以將事件綁定放在對象中。

$(document).on({
    mousedown: function() { ... },
    mouseup: function() { ... }
}, '.item');

除非我對這個問題有誤解,否則此片段是通過鏈接事件處理程序進行mousedown / mouseup計時器委派的有效示例。 鏈接適用於document元素,而不適用於委托后代,但最終結果似乎與您要查找的行為相匹配。

在這里, this是已過濾的后代元素,它實際上是事件目標。

 $(document) .on('mousedown', '.has_timer', function() { clearTimeout(this.downTimer); $('#this_identity').text(this.className); this.downTimer = setTimeout(function() { alert('mousedown > 2 sec'); }, 2000); }) .on('mouseup', '.has_timer', function() { clearTimeout(this.downTimer); }); 
 .has_timer { border: 1px solid green; margin: 1em; padding: 1em; } .no_timer { border: 1px solid blue; margin: 1em; padding: 1em; } .this_test { border: 1px solid gray; margin: 1em; padding: 1em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="has_timer first_has_timer">This element has a mousedown timer.</div> <div class="no_timer">This element does not have a timer.</div> <div class="has_timer other_has_timer">This other element has a mousedown timer.</div> <div class="no_timer">This other element does not have a timer.</div> <div class="this_test">"this" className: <span id="this_identity"></span></div> 

暫無
暫無

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

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