帮助我了解如何将功能附加到事件

时间:2011-02-09 11:06:27

标签: javascript javascript-events

    // param {name:'name', click : function(ev[,arg1, arg2] ){}, focus:function(ev[,arg1, arg2] ){} }
    ToggleButton = function(params) {
         var btn = document.getElementId(params.name);
         // how to hook the above click function passed using 
         // params and pass additional params along with it like function(ev[,arg1,arg2]) 
         btn.onclick = params.click;
    }

我正在尝试实现扩展链接按钮,就像切换按钮一样。现在我想能够附上上面指定的事件,但我没有得到它如何将它附加到按钮,以便我可以享受如下的代码?

new ToggleButton({name: 'toggle1', "click" :  function(evt, obj1, obj1){ 
        //function body 
    }
});

2 个答案:

答案 0 :(得分:2)

我会这样做:

<a href="foo.html" id="toggle1">Toogle</a>


var ToggleButton = function(params) {
    var btn  = document.getElementById(params.id);
    var evt  = 'on' + params.evt;
    btn[evt] = params.action;    
    return;
}

ToggleButton({
    id:      'toggle1',
    evt:     'click',
    action:  function(evt){
        var clickedElement = this;
        alert('My href is '+ clickedElement.getAttribute('href'));

        // Prevent the browser from following the href, 
        // just in case you set this attribute
        var e = evt || window.event;
        e.preventDefault();
    }
});

答案 1 :(得分:0)

你可以这样做:

ToggleButton = function( params) {
      var button = document.getElementById( params.name);
      if ( button) {
         button.onclick = params.click;
      }
}