jQuery - 将事件处理程序从<input />复制到<div>一个元素到另一个元素</div>

时间:2011-08-04 03:21:26

标签: jquery javascript-events dom-manipulation

我不相信任何类似的现有问题都会回答这个问题。

我正在开发一个插件,可以将<input type='checkbox' />转换为具有两种切换状态的<div>。使用的基本思路是:

$('div .checkboxContainer').prettyBox();

插件本身的伪代码是:

$.fn.prettyBox = function(){
    return this.each(function(){
        $(this).find(':checkbox').each(function(){
           .. grab all event handlers on the current <input>
           .. create a new <div>
           .. attach all of the <input>'s event handlers to the <div>
           .. hide the <input>
           .. place the <div> where the <input> used to live
        });  
    };
};

其他提出类似问题的人一直关注复制单个事件,例如click处理程序。为了保持插件的灵活性,我认为重要的是我的代码循环连接到输入的所有内容并将其复制过来。

2 个答案:

答案 0 :(得分:4)

试试这个

$.fn.prettyBox = function(){
    return this.each(function(){
        $(this).find(':checkbox').each(function(){
           //Grabs all the events
           var events = $(this).data("events");
           var $div = $("<div />");

           //Loop through all the events
           $.each(events, function(i, event) {
             //Loop through all the handlers attached for a event
             $.each(event, function(j, h) {
               //Bind the handler with the event 
               $div.bind(i, h.handler);
             });
           });

           $(this).hide().after($div);
        });  
    };
};

答案 1 :(得分:1)

我认为如果事件也使用jQuery绑定,你可以使用$('#elem')获取所有事件.data(“events”)

Soure: https://stackoverflow.com/questions/2518421/jquery-find-events-handlers-registered-with-an-object