jQuery克隆问题 [英] jQuery clone problem
问题描述
我正在尝试克隆一个div并更改此div中输入字段的名称. 它适用于大多数浏览器,但IE 7不会更改输入字段的名称属性.
I am trying to clone a div and change the names of the input fields in this div. It works great for most of the browsers but IE 7 does not change the name attribute of the input fields.
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">
Firefox: (works)
<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 (bug):
<INPUT value="Hello World" name=test jQuery1273063303968="4">
如您所见,IE7的名称未更改为test2.
As you see the name of IE7 does not change to test2.
是否有明显的原因或解决方法?
Is there any obvious reason or work around?
推荐答案
我现在可以修复它. 只要输入字段未附加到dom,您就可以更改名称,并且单选按钮可以再次正常工作.
I could fix it for now. As long as an input field is not attached to the dom you can change the name and the radio buttons work properly again.
// Old Code
$("div:last").clone(true).children("input").attr("name","newName");
// New Code
$("div:last").clone(true).children("input").fixCloneBug ("newName");
要减少执行时间,仅复制jQuery事件,className和type属性.
To lower the execution time only the jQuery Events, the className and the type attribute are copied.
fixCloneBug方法:
fixCloneBug Method:
(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功能:
Maybe you think $newElem.attr('name', this.name );
is useless however it allows me to use a jQuery 1.4 feature:
.fixCloneBug (function(i,oldname){ return oldname+"_new" })
这篇关于jQuery克隆问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!