我正在努力学习和理解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”。
发布于 2013-03-03 23:08:50
这在jQuery中无效:
$("input:file", myInput ).attr({ id: id, name: id });在上面的代码中,myInput将更改属性,但第一个输入元素不会更改。
首先将克隆的对象添加到DOM中:
var myInput = $(".File:first").clone(true).appendTo("body");然后更改属性:
myInput.attr({ id: id, name: id });发布于 2013-03-03 22:53:19
您不会对克隆的对象执行任何操作。要么添加克隆的对象,要么替换为现有对象。
注意:使用.clone()方法时,可以在(重新)将克隆的元素或其内容插入文档之前对其进行修改。 (http://api.jquery.com/clone/)
如果只想更新id和名称,可以使用这个JS fiddle 。
JS:-
$(document).ready(function () {
var lastId = 1;
$("#AddFile").click(function () {
var id = "File" + ++lastId;
var myInput = $(".File:first");
$(myInput).attr({
id: id,
name: id
});
});
});发布于 2013-03-03 23:07:21
看起来运行得很好。我已经初始化了var lastId并使用appendTo()将克隆放入页面:
http://jsfiddle.net/yWVhC/2/
var lastId = 0;
$("#AddFile").click(function () {
var id = "File" + ++lastId;
var myInput = $(".File:first").clone(true).appendTo('body');
// 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
});
});如果这还不能涵盖问题,那么您需要更清楚地了解这个问题。
https://stackoverflow.com/questions/15186672
复制相似问题