简体   繁体   English

jQuery-如何在附加选择器上链接事件

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

I'm trying to adapt the code from this answer to a jQuery appended element, without using any "flag" variables. 我试图将代码从此答案改编为jQuery附加元素,而不使用任何“标志”变量。

Original code is : 原始代码是:

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

So I can't see how to use it with document : 所以我看不到如何在document使用它:

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

I've tried with 我尝试过

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

but no luck. 但没有运气。

This can't be done using chaining, because .on() returns the object it was called on, and that doesn't include the selector that it delegates to. 这不能使用链接来完成,因为.on()返回调用它的对象,并且不包括它委托给它的选择器。

Instead, you can put the event bindings in an object. 相反,您可以将事件绑定放在对象中。

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

Unless I'm misunderstanding the question, this snippet is a working example of mousedown / mouseup timer delegation via chained event handlers. 除非我对这个问题有误解,否则此片段是通过链接事件处理程序进行mousedown / mouseup计时器委派的有效示例。 The chaining works on the document element, not on the delegated descendant, but the end result seems to match up with the behavior you're looking for. 链接适用于document元素,而不适用于委托后代,但最终结果似乎与您要查找的行为相匹配。

Here, this is the filtered the descendant element that is actually the event target. 在这里, 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