jquery - 将事件处理程序从 &lt;input&gt; 复制到 <div> 一个元素到另一个元素

标签 jquery jquery-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处理程序。为了保持插件的灵活性,我认为我的代码循环遍历附加到输入的所有内容并将其复制过来非常重要。

最佳答案

试试这个

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

关于jquery - 将事件处理程序从 &lt;input&gt; 复制到 <div> 一个元素到另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6935837/

相关文章:

javascript - JQuery - 点击动画元素

javascript - 输入类型之间的 DOM/jQuery 事件传播差异

javascript - 通过html图像元素对象显示图像

jQuery - 移动元素并返回到其之前的确切位置?

jQuery prev、prevUntil 或最近的中断标记然后删除

jquery - ReplaceWith() 不删除原始元素

php - ajax将javascript变量发布到同一页面中的php

jquery - 带有缩略图轮播的 Twitter bootstrap 图片库

JavaScript 媒体查询

javascript - 在不调用父托管脚本的情况下让子页面调整父页面大小?