jQuery克隆问题

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

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

HTML

 

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 :(有效)

IE8(正常)

IE7(bug):

如您所见,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.4function:

.fixCloneBug (function(i,oldname){ return oldname+"_new" })

试试这个(原始代码)

 $(some_cloned_element).each(function(i, elem){ var newName = "yay_i_love_my_new_name"; if ($.browser.msie === true){ // evil browser sniffing *cries* $(elem).replaceWith(document.createElement( this.outerHTML.replace(/name=\w+/ig, 'name='+newName+'_'+i) )); } else { $(elem).attr('name',newName+'_'+i); } $("body").append(some_cloned_element); }); 

检查i = 50然后中断/退出

更好的方法:使用name作为数组,如name=picture[]

Refernece

如果您在发布表单时平移访问这些作为一个集合,则无需更改名称 – 只是不要在括号中放置一个值,当您在服务器端获取arrays时它将为您递增:

如果你需要能够通过js的索引访问每一个,你可以使用get选择器返回的相应集合。 或者您可以指定test_1等ID属性。

单选按钮的简单解决方案是:

 $("div:last").find("radio").each(function(){ var name="someNewName"; var id="someNewId"; if (!$.browser.msie || parseInt($.browser.version) > 7) { this.name = name; this.id=id; } else { (this).attr("outerHTML", ""); } }); 

这将改变元素的outerHTML ,以便覆盖元素的HTML(单选按钮)。 同样的解决方案也适用于:其他控件的find(“input”)/ find(“checkbox”)。