jquery的clone方法bug的修复

项目中多次使用了iframe,但是操作起来是比较麻烦,项目中的现实情况是最外面是一个form,里面嵌套一个iframe,下面是一个其他的数据,在form提交的时候将iframe的数据和其他的数据一块提交。
     现在采用的是最原始的办法就是在form提交之前,将iframe里面的input,select,textarea都clone到外面的form里面,然后进行表单提交,随便说明一下,ifram表单里面可能有文件上传的input. 虽然感觉这个方法不好,但是比较简单,如果各位博友有好的办法欢迎一块讨论。直接上项目中的的代码吧:

Js代码 :

  1. $("iframe").find("input").each(function(){ 
  2.     $("#formHidden").append($(this).clone()); 
  3. }); 
  4. $("iframe").find("select").each(function(){ 
  5.     $("#formHidden").append($(this).clone()); 
  6. }); 
  7. $("iframe").find("textarea").each(function(){ 
  8.     $("#formHidden").append($(this).clone()); 
  9. }); 

      另外,测试发现,textarea和select的jquery的clone方法有问题,textarea和select的值clone的时候会丢掉,发现这个是jquery的一个bug,在网上发现一个插件,下载地址如下:https://github.com/spencertipping/jquery.fix.clone/blob/master/jquery.fix.clone.js,上不了的可以看下代码,比较简单。就是在clone的时候将val再重新赋值一下,如果知道这个了,也可以不用这个插件,自己写。
Js代码:

  1. // Textarea and select clone() bug workaround | Spencer Tipping 
  2. // Licensed under the terms of the MIT source code license 
  3.  
  4. // Motivation. 
  5. // jQuery's clone() method works in most cases, but it fails to copy the value of textareas and select elements. This patch replaces jQuery's clone() method with a wrapper that fills in the 
  6. // values after the fact. 
  7.  
  8. // An interesting error case submitted by Piotr Przybył: If two <select> options had the same value, the clone() method would select the wrong one in the cloned box. The fix, suggested by Piotr 
  9. // and implemented here, is to use the selectedIndex property on the <select> box itself rather than relying on jQuery's value-based val(). 
  10.  
  11. (function (original) { 
  12.   jQuery.fn.clone = function () { 
  13.     var result           = original.apply(this, arguments), 
  14.         my_textareas     = this.find('textarea').add(this.filter('textarea')), 
  15.         result_textareas = result.find('textarea').add(result.filter('textarea')), 
  16.         my_selects       = this.find('select').add(this.filter('select')), 
  17.         result_selects   = result.find('select').add(result.filter('select')); 
  18.  
  19.     for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val()); 
  20.     for (var i = 0, l = my_selects.length;   i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex; 
  21.  
  22.     return result; 
  23.   }; 
  24. }) (jQuery.fn.clone); 

原创链接:http://www.software8.co/wzjs/jquery/2799.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值