开发者

Copying event handlers from an <input> to a <div> one element to another

开发者 https://www.devze.com 2023-03-25 08:22 出处:网络
I don\'t believe any similar existing questions answer this one. I am developing a plugin that will turn <input type=\'checkbox\' /> into a <div> with two toggle states.The basic idea for

I don't believe any similar existing questions answer this one.

I am developing a plugin that will turn <input type='checkbox' /> into a <div> with two toggle states. The basic idea for use is:

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

The pseudo code for the plugin itself is:

$.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
        });  
    };
};

Others who have asked similar questions have been concerned with copying single events, such as a click handler. To maintain plugin flexibility, I thin开发者_开发百科k it's important that my code loop through everything attached to the input and copy it over.


Try this

$.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);
        });  
    };
};


I think if the events are also bound using jQuery, you can get all events using $('#elem').data("events")

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

0

精彩评论

暂无评论...
验证码 换一张
取 消