在jQuery中,您可以轻松地做到这一点:

$("#foo").focus(function () {
    // Do this.
}).blur(function () {
    // Do that.
});


我们可以在纯JavaScript中做类似的事情,这样就不必在两个单独的函数中重复#foo吗?

最佳答案

使用变量;真!

var foo = document.getElementById('foo');

foo.addEventListener('focus', function () {
    // Do this.
});

foo.addEventListener('blur', function () {
    // Do that.
});


或帮助者,如果您愿意:

function on(eventSource, listeners) {
    for (var k in listeners) {
        if (Object.prototype.hasOwnProperty.call(listeners, k)) {
            eventSource.addEventListener(k, listeners[k]);
        }
    }
}

on(foo, {
    focus: function () {
        // Do this.
    },
    blur: function () {
        // Do that.
    }
});


或链接助手:

function chainOnly(obj) {
    var wrapper = {};

    function createChainWrapper(func) {
        return function wrapped() {
            func.apply(obj, arguments);
            return wrapper;
        };
    }

    for (var k in obj) {
        if (typeof obj[k] === 'function') {
            wrapper[k] = createChainWrapper(obj[k]);
        }
    }

    return wrapper;
}

chainOnly(foo)
    .addEventListener('focus', function () { /* … */ })
    .addEventListener('blur',  function () { /* … */ });

09-30 16:03
查看更多