Javascript:作为属性的函数

时间:2015-04-30 01:09:17

标签: javascript function

说我有这样的代码:

function on(loc,type,func){
    loc.addEventListener(type, function(e){
        func(e);
    });
}

如果我这样打电话:

on(document.getElementById('test'),"click",function(){
    alert('You clicked!');
});

它可以工作,但我希望能够像这样调用on函数:

document.getElementById('test').on('click', function(){
    alert('You clicked!');
});

如何能够像这样调用它?

2 个答案:

答案 0 :(得分:1)

正如已经指出的那样,DocumentElement没有.on()方法。但是!

但是,您可以按extending the prototype添加一个,添加新属性并在所有元素上使用您的功能。这很容易(我稍后会提供一个简单的例子),但它也是widely considered to be a bad practice。所以在你尝试这个之前,要明白Javascript绝对能让它成为可能......但这并不意味着它是个好主意。

现在,那个例子:

Element.prototype.test = function() {
   console.log("Successfully extended the prototype of a native object!");
}

document.getElementById("footer").test();

答案 1 :(得分:0)

您无法执行此操作,因为DocumentElement没有属性(或允许您创建on函数的属性(我知道)。

你可以做类似的事情,例如修改on函数来处理给定元素的onlcick事件。我还没有测试下面的代码,但它应该给你一个想法:

function on (element) {
    var obj = {
        clickEvent : function () {
            element.onclick = function () {
                alert("you clicked");
            }
        }
    };
    return obj;

}

var theElement = document.getElementById("test");
on(theElement).clickEvent();
相关问题