【问题标题】:Copying event handlers from an <input> to a <div> one element to another将事件处理程序从 <input> 复制到 <div> 一个元素到另一个元素
【发布时间】:2021-03-06 02:48:08
【问题描述】:

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

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

$('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 处理程序。为了保持插件的灵活性,我认为我的代码循环遍历输入的所有内容并将其复制过来是很重要的。

【问题讨论】:

    标签: jquery jquery-events dom-manipulation


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-21
        • 2010-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 2012-09-27
        相关资源
        最近更新 更多