我正在尝试学习和理解 jquery,但我在使用多个选择器时遇到了一些问题。当我的一个选择器中有一个克隆的 jquery 对象时,我似乎无法更新属性、id 和 name。
HTML
<div class="File">
Choose a file:
<input id="File0" name="File0" type="file" />
</div>
<input id="AddFile" type="button" value="Add a File" />
<div id="div1"></div>
<div id="div2"></div>
jQuery
var lastId = 0;
$(document).ready(function () {
$("#AddFile").click(function () {
var id = "File" + ++lastId;
var myInput = $(".File:first").clone(true);
// Why doesn't this update the input of type 'file'
// on the page when selecting multiple selectors?
$("input:file", myInput ).attr({ id: id, name: id });
//But if you have omit 'myInput' like this, it will work.
// $("input:file").attr({ id: id, name: id });
//This will also work
//$('#div1, #div2').attr({ id: id, name: id });
//If I add in the cloned object at the end, it will only
//modify the input element and not the div with class=File
//imyInput.insertBefore("#AddFile");
});
});
当我运行上面的代码时。无论我点击 AddFile 按钮多少次,dom 仍然读取 id="File0" name="File0" type="file"。"