jquery无法使用其id克隆元素

时间:2013-10-07 18:57:37

标签: javascript jquery

我正在尝试使用Jquery克隆 div ,然后更改其子项的id之一以及另一个元素之后的add:

var s = $('#runwell1').clone().wrap('<div>');
s.find('#tag' + runNum).attr('id', 'tag' + (++runNum));
$('#addrun').before(s.parent().html());

但此代码无效。怎么了?如何使用id ??

进行克隆

编辑这里是div的html:

<div class="well well-large RunWell" id="#runwell1">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

    <!-- Form Name -->
    <legend>Run 1</legend>

    <!-- Multiple Radios -->
    <div class="control-group">
        <label class="control-label" for="radios">System :</label>
        <div class="controls">
            <label class="radio" for="radios-0">
                <input type="radio" name="radios" id="radios-0" value="op" checked="checked">
                OPE
            </label>
            <label class="radio" for="radios-1">
                <input type="radio" name="radios" id="radios-1" value="mxwl">
                Maxwell
            </label>
        </div>
    </div>

    <!-- Textarea -->
    <div class="control-group">
        <label class="control-label" for="textarea">Tools :</label>
        <div class="controls">
            <input type="text" class="tags" id="tag1" value="Amsterdam,Washington,Sydney,Beijing" data-role="tagsinput" />
        </div>
        </br>
        <div class="SystemFiles" data-role="collapsible">
            <!-- File Button -->
            <div class="control-group">
                <label class="control-label" for="filebutton">OP  DLIS </label>
                <div class="controls">
                    <input id="filebutton" name="filebutton" class="input-file" type="file">
                </div>
            </div>
        </div>

3 个答案:

答案 0 :(得分:2)

您还需要更改.clone()的div,以避免双ID

试试这个:

var runNum = 1;
var s = $('#runwell' + runNum)
    .clone()
    .attr('id', '#runwell' + (++runNum))
    .wrap('<div>');

s.find('#tag' + runNum).attr('id', 'tag' + (++runNum));
$('#addrun').before(s);

演示here

答案 1 :(得分:2)

你的身份证明有# ..

id="#runwell1" <---here

<div class="well well-large RunWell" id="#runwell1">
                          //-------------^----here

删除标记中的#

并且您的ID选择器将起作用..

答案 2 :(得分:0)

var s = $('#runwell1').clone().wrap('<div>');

s将引用选择器当它运行时的内容。它不包含在DOM中操作的内容。