2016-03-01 32 views
1

我試圖修改代碼從this answer jQuery附加元素,而不使用任何「標誌」變量。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') 

,但沒有運氣。

回答

1

這不能使用鏈接完成,因爲.on()返回被調用的對象,並且不包含它委託給的選擇器。

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

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

除非我誤解的問題,這個片段是通過鏈接事件處理程序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>

相關問題