gpt4 book ai didi

javascript - 测试创建 DOM 组件列表的函数

转载 作者:行者123 更新时间:2023-11-28 02:31:56 25 4
gpt4 key购买 nike

我有一个创建组件数组的函数。每个组件都是一个外部 div 和一些内部 div。

function createDivs(quizQuestions) {
var returnElements = new Array();
$.each(quizQuestions.questions, function(i, val){

// create the div.
quizDiv = $('<div class="questionContainer radius">')
questionDiv = $('<div class="question"><b><span>QuestionText</span></b></div>');
quizDiv.append(questionDiv);

// Now change the question div text.
questionDiv.text = val.question;
answerDiv = $('<div class="answers">');
// ...
// ...
// Now the answers.
questionDiv.append(answerDiv);
returnElements[i] = quizDiv;
});
return returnElements;

我传递 JSON 例如:

   {questions:[{"question":"Name the best Rugby team?",
"answers":["Leinster", "Munster", "Ulster", "Connaught"],
"correct_answer":"Leinster"},
{"question":"Name the best DJ?",
"answers":["Warren K", "Pressure", "Digweed", "Sasha"],
"correct_answer":"Leinster"}]};

我想编写一个简单的单元测试,以便我可以测试返回的 div 数组是否有意义

有什么建议吗?

此外,我最好返回 DOM 组件还是仅返回文本?后者更容易测试。

谢谢。

最佳答案

不确定您到底想要测试什么,但在字符串中创建尽可能多的 html 以减少函数调用的性能要高得多。另外,追加成本很高,因此最终为 JSON 表示的所有新内容制作一个字符串将是最大的性能提升。

在我看来,它还使代码更具可读性,因为片段的顺序与 html 编辑器中的顺序相同

示例(我更喜欢创建所有字符串片段的数组,连接也常用):

var newcontent = [];
$.each(quizQuestions.questions, function(i, val) {
newcontent.push('<div class="questionContainer radius">');
newcontent.push('<div class="question"><b><span>' + val.question + '< /span></b > < /div>');

$.each(val.answers, function(idx, answer) {
newcontent.push('<div class="answers">' + answer + '</div > ')
})

newcontent.push(' </div></div > ');
});

然后将内容添加到 DOM:

$('#someDiv').append( newcontent.join(''));

免责声明:未完全检查标签的正确关闭/嵌套。

关于javascript - 测试创建 DOM 组件列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14015703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com