gpt4 book ai didi

javascript - 将两个问题动态加载到单独的表单中以及它们的适当答案选项

转载 作者:行者123 更新时间:2023-11-30 16:28:51 27 4
gpt4 key购买 nike

我想要一个按钮,一旦按下。将两个问题(问题 1 和问题 2)动态加载到单独的表单中。但它也包含问题3个答案可供选择。目前我的 for 循环添加了一组额外的 3 个答案(问题 2 的答案)以供从问题 1 中选择

输出看起来像下面这样:

需要是 QUESTION 1(YES,NO,OTHER)和 QUESTION 2(YES2,NO2,OTHER2)

image example

代码

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="center col-xs-12">
<button class="contentBtn btn"><label for="contentBtn">CONTENT</label></button>
</div>
<div class="row-2 center col-xs-12"></div>
<script src="js/jquery-1.11.3.min.js" type='text/javascript'>
</script>
<script>
$('.contentBtn').click(function(){
var contentArray = [

["QUESTION1?", "YES", "NO", "OTHER"],
["QUESTION2?", "YES2", "NO2", "OTHER2"]
];

for (var i = 0; i < contentArray.length; i++){
$('.row-2').append("<form><span class='question'>" + contentArray[i][0] + "<\/span><br>")
for (var x = 1; x < 4; x++){
$('form').append("<input type='radio' value='" + contentArray[i][x] + "'>" + contentArray[i][x] + "");
}
$('.row-2').append("<\/form><br>");
}
});

</script>
</body>
</html>

最佳答案

简短的回答是您在附加“表单”,这意味着您在 DOM 上附加每个表单。该代码还破坏了 DOM。输入未关闭,并且绝不能像示例中那样以部分方式进行追加。

// Always favor the 'on' events instead of the 'click' events.
$('.contentBtn').on('click', function () {
var contentArray = [
['QUESTION1?', 'YES', 'NO', 'OTHER'],
['QUESTION2?', 'YES2', 'NO2', 'OTHER2']
];

// we are going to use a for each on the first item,
// we could use a for as well but it just is really messy.
// remember that variables are defined at function scope, not block scope.
$(contentArray).each(function (index, item) {
// our item in the array is directly coming in to us now.
// do not add incomplete html blocks to the dom, always
// create them and then add them!
var newContent = $('<form><span class="question">' +
item[0] + '</span><br></form><br>');

// now we will foreach, but instead of going by a length of 4,
// I am looking at the actual length of the array.
for (var i = 1; i < item.length; i++) {

// we are going to precreate our dom object.
var answerContent = $('<input type="radio" value="' +
item[i] + '">' + item[i] + '</input>');

// now we are going to append the object to our form object.
newContent.append(answerContent);
}

// now that the structure is complete we will append the browser dom.
$('.row-4').append(newContent);
});
});

我已经为您创建了一个带有评论的更正 fiddle 。 https://jsfiddle.net/t9h91nbk/

希望这对您有所帮助。

关于javascript - 将两个问题动态加载到单独的表单中以及它们的适当答案选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33660606/

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