微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jQuery克隆问题

我试图克隆一个div并更改此div中输入字段的名称.
它适用于大多数浏览器,但IE 7不会更改输入字段的name属性.

演示:http://jsbin.com/iduro/7

HTML

<body>
  <pre></pre>
  <div><input value="Hello World" name="test"></div>
</body>

JS

var lastRow = $("body div:last"),newRow  = lastRow.clone(true)
              .show()
              .insertAfter(lastRow);

newRow.find('input').attr("name","test2");

$("pre").text( newRow[0].innerHTML );

结果:

Firefox :(有效)
 < input value =“Hello World”name =“test2”>

IE8(作品)
< INPUT value =“Hello World”name = test2 jQuery1273063250500 =“4”>

IE7(错误):
< INPUT value =“Hello World”name = test jQuery1273063303968 =“4”>

如您所见,IE7的名称不会更改为test2.

有没有明显的理由或解决方法

解决方法

我现在可以解决它.
只要输入字段未附加到dom,您就可以更改名称,并且单选按钮可以再次正常工作.

// Old Code
 $("div:last").clone(true).children("input").attr("name","newName");

// New Code
 $("div:last").clone(true).children("input").fixCloneBug ("newName");

要降低执行时间,只复制jQuery Events,className和type属性.

fixCloneBug方法

(function( $)
{


    if ( ! $.browser.msie || parseInt( $.browser.version ) > 7 )
        // NO FIX FOR IE 7+ FF WEBKIT
        $.fn.fixCloneBug = function( newName ){ return this.attr( "name",newName ) };
    else
        // FIX IE 5-7
        $.fn.fixCloneBug = function( newName )
        {
            var $cloned = $();

            this.each(function( )
            {
                    /* -._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._

                       Create a new element with className and jQuery events of the buggy element

                    */          

                    var     $elem    = $(this),$newElem = $(document.createElement( $elem.attr('tagName') ));

                            // USE SAME TYPE

                    $newElem.attr('type',$elem.attr('type') );


                            // SET NAME
                    $newElem.attr('name',this.name );
                    $newElem.attr('name',newName );

                            // ADD TO DOM

                    $newElem.insertBefore( $elem );

                            // CLONE EVENTS
                    $newElem.data( "events",$elem.data("events") );

                            // CLASS NAME
                    $newElem.attr('className',this.className );

                    /* -._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._

                       Delete buggy element 

                    */

                    $elem.remove();


                    // Add to result
                    $cloned.push($newElem);
            })

            return $cloned;

        }

}(jQuery));

也许你认为$newElem.attr(‘name’,this.name);没用,但它允许我使用jQuery 1.4功能

.fixCloneBug(function(i,oldname){return oldname“_new”})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐