我想动态创建html元素,但是当尝试在循环中的容器中追加一些元素时,它无效。为什么呢?
var html = '<div id="' + question.id + '"> \
<div class="quizlib-question"> \
<div class="well well-sm quizlib-question-title"><strong>' + question.title + '</strong></div> \
<div class="quizlib-question-answers"></div> \
</div> \
</div>';
for (var i=0; i < question.choices.length; i++) {
var answerHTML = '<div class="radio quizlib-question-answer"><label><input type="radio" name="' + question.name + '" value="' + i + '">' + question.choices[i] + '</label></div>';
//this part is nor working
$(html).find(".quizlib-question-answers").append(answerHTML);
}
$('body').append(html);
答案 0 :(得分:4)
这一行:
$(html).find(".quizlib-question-answers").append(answerHTML);
不更新字符串变量html
,它会附加到最初使用html
内容创建的jQuery对象。
要解决此问题,请将jQuery对象附加到dom,而不是html
。首先创建jQuery对象
var $html = $('<div id="' + question.id + '"> \
<div class="quizlib-question"> \
<div class="well well-sm quizlib-question-title"><strong>' + question.title + '</strong></div> \
<div class="quizlib-question-answers"></div> \
</div> \
</div>');
(注意,我按照惯例使用$
为jQuery对象添加前缀)
然后正常追加:
for (var i=0; i < question.choices.length; i++) {
var answerHTML = '<div class="radio quizlib-question-answer"><label><input type="radio" name="' + question.name + '" value="' + i + '">' + question.choices[i] + '</label></div>';
//this part is nor working
$html.find(".quizlib-question-answers").append(answerHTML);
}
最后将其添加到DOM
$('body').append($html);
答案 1 :(得分:4)
问题是因为您将html
附加到DOM,但您从未更新html
变量。相反,你要从该变量创建一个jQuery对象,但你永远不会对它做任何事情。
要解决此问题,请尝试立即从html
创建一个jQuery对象,然后在执行循环之前将其附加到DOM,如下所示:
var $html = $('<div id="' + question.id + '"> \
<div class="quizlib-question"> \
<div class="well well-sm quizlib-question-title"><strong>' + question.title + '</strong></div> \
<div class="quizlib-question-answers"></div> \
</div> \
</div>').appendTo('body');
for (var i = 0; i < question.choices.length; i++) {
var answerHTML = '<div class="radio quizlib-question-answer"><label><input type="radio" name="' + question.name + '" value="' + i + '">' + question.choices[i] + '</label></div>';
$html.find(".quizlib-question-answers").append(answerHTML);
}
答案 2 :(得分:1)
与提到的评论者一样,在开始搜索您创建的DOM元素之前,必须附加到正文。例如:
var html = '<div id="' + question.id + '"> \
<div class="quizlib-question"> \
<div class="well well-sm quizlib-question-title"><strong>' + question.title + '</strong></div> \
<div class="quizlib-question-answers"></div> \
</div> \
</div>';
$('body').append(html);
for (var i=0; i < question.choices.length; i++) {
var answerHTML = '<div class="radio quizlib-question-answer"><label><input type="radio" name="' + question.name + '" value="' + i + '">' + question.choices[i] + '</label></div>';
//this part is nor working
$(".quizlib-question-answers").append(answerHTML);
}