zoukankan      html  css  js  c++  java
  • jquery的clone方法bug的修复select,textarea的值丢失

     项目中多次使用了iframe,但是操作起来是比较麻烦,项目中的现实情况是最外面是一个form,里面嵌套一个iframe,下面是一个其他的数据,在form提交的时候将iframe的数据和其他的数据一块提交。 
         现在采用的是最原始的办法就是在form提交之前,将iframe里面的input,select,textarea都clone到外面的form里面,然后进行表单提交。

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

    // Textarea and select clone() bug workaround | Spencer Tipping
    // Licensed under the terms of the MIT source code license
    
    // Motivation.
    // 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
    // values after the fact.
    
    // 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
    // and implemented here, is to use the selectedIndex property on the <select> box itself rather than relying on jQuery's value-based val().
    
    (function (original) {
      jQuery.fn.clone = function () {
        var result           = original.apply(this, arguments),
            my_textareas     = this.find('textarea').add(this.filter('textarea')),
            result_textareas = result.find('textarea').add(result.filter('textarea')),
            my_selects       = this.find('select').add(this.filter('select')),
            result_selects   = result.find('select').add(result.filter('select'));
    
        for (var i = 0, l = my_textareas.length; i < l; ++i) $(result_textareas[i]).val($(my_textareas[i]).val());
        for (var i = 0, l = my_selects.length;   i < l; ++i) result_selects[i].selectedIndex = my_selects[i].selectedIndex;
    
        return result;
      };
    }) (jQuery.fn.clone);

    内容摘自:http://asialee.iteye.com/blog/1753447 

  • 相关阅读:
    快乐前端-图片预加载
    浅谈canvas绘画王者荣耀--雷达图
    浅谈CSS3动画的凌波微步--steps()
    车大棒浅谈jQuery源码(二)
    车大棒浅谈jQuery源码(一)
    车大棒浅谈for循环+canvas实现黑客帝国矩形阵
    浅谈JavaScript 函数作用域当中的“提升”现象
    清除浮动塌陷的4种经典套路
    可以看电影的微信公众号
    Mac安装protobuf编译Java
  • 原文地址:https://www.cnblogs.com/fm168/p/7087300.html
Copyright © 2011-2022 走看看