简体   繁体   中英

How clone div jquery html

I need to clone some parts of a HTML page but I've got something wrong.

<div id="question_answer">
    <label for="label_questions">Questions</label>
    <input type"text" name="questions_name">
    <div id="answer">
        <label for="label_answer">Answer</label>
        <input type="text" name="answers_name">
    </div>
</div>

Suppose there is a number of questions that we know X (example x=4 ) my code is:

var div_questions_answer = $('#question_answer');
var div_answer = $('#answer');

for (var i = 0; i < X; i++) {
    var label = $('label[for^="label_questions"]').clone();
    div_answer.append(label);
}
div_questions_answer.append(div_answer);

I can't see the four label but I can see only one!Anyone can help me?

尝试这个

$QuestionAns = $('#question_answer').clone();

Why can't you do this?

var div_answer = $("#answer");
for (var i = 0; i < 4; i++) {
    $('#question_answer > label[for^="label_questions"]').clone().appendTo("#answer");
}

FIDDLE

@RejithRKrishnan's comment was reasonable in regard to there must be clone of a single label element. But $('label[for^="label_questions"]') selector gets multiple elements if they are presented in markup (after at leat first loop iteration).
Use the following solution to attach a single clone to the div_answer element:

var div_questions_answer = $('#question_answer');
var div_answer = $('#answer');
var label = $('label[for^="label_questions"]:first').clone();

for (var i = 0; i < 4; i++) {
    label.clone().appendTo(div_answer);
}
div_questions_answer.append(div_answer);

https://jsfiddle.net/bg9vbge9/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM