泛前端开发

泛前端开发
javascript
Comments

Jquery One 工作原理


先看一下源码实现

//Attach a handler to an event for the elements. The handler is executed at most once per element.  
on: function(types, selector, data, fn, /*INTERNAL*/ one) { //...    
    if (one === 1) {
        origFn = fn;
        fn = function(event) {
            // Can use an empty set, since event contains the info            
            jQuery().off(event);
            return origFn.apply(this, arguments);
        }; // Use same guid so caller can remove using origFn        
        fn.guid = origFn.guid || (origFn.guid = jQuery.guid++);
    } // ....      
}, one: function(types, selector, data, fn) {
    return this.on(types, selector, data, fn, 1);
},
$("body").one("click", ".main_container", function() {
    alert("This displays once for the first .foo clicked in the body.");
});

相当于

$("body").on("click", ".main_container", function(event) {
    jQuery().off(event);
    alert("This displays once for the first .foo clicked in the body.");
});

-EOF-



原创文章,版权声明:自由转载-非商用-非衍生-保持署名 | Creative Commons BY-NC-ND 3.0

Comments