gpt4 book ai didi

使用 DOM 和 appendChild 的函数中的 JavaScript 数组

转载 作者:行者123 更新时间:2023-12-03 16:38:12 26 4
gpt4 key购买 nike

我的添加问题和答案的简单脚本有问题。更具体地说,随着对以下问题的进一步回答的增加,第二个问题继续从第一个问题停止的地方命名答案——例如

问题一答案a,b,c

问题二答案a,b,d

我想我必须使用一个数组,每个问题 -> 自己的数组。

  n = 1;

function add_question() {

var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
textarea.className = "form-control";
textarea.id = "pytanie_id_" + n;
textarea.name = "data[" + n + "][pytanie]";
textarea.autocomplete = "off";
var addone = document.createElement("input");
addone.type = "button";
addone.value = "+";
addone.id = "id_" + n;
addone.className = "btn btn-success-my";
addone.innerHTML = "<span class=\"glyphicon glyphicon-plus\">";
var label_pyt = document.createElement("label");
label_pyt.className = "col-md-4 control-label";
label_pyt.for = "pytanie_id_" + n;
label_pyt.innerHTML = "Question " + n + ".";
var label_odp_a = document.createElement("label");
label_odp_a.className = "col-md-4 control-label";
label_odp_a.for = "odp_a_id_" + n;
label_odp_a.innerHTML = " A";
var input_odp_a = document.createElement("input");
input_odp_a.id = "odp_a_id_" + n;
input_odp_a.name = "data[" + n + "][odp_a]";
input_odp_a.type = "text";
input_odp_a.className = "form-control input-md";
input_odp_a.autocomplete = "off";
var label_odp_b = document.createElement("label");
label_odp_b.className = "col-md-4 control-label";
label_odp_b.for = "odp_b_id_" + n;
label_odp_b.innerHTML = " B";
var input_odp_b = document.createElement("input");
input_odp_b.id = "odp_b_id_" + n;
input_odp_b.name = "data[" + n + "][odp_b]";
input_odp_b.type = "text";
input_odp_b.className = "form-control input-md";
input_odp_b.autocomplete = "off";
//addone.addEventListener("onclick", function(n){add_answer(n);});
var divquest = document.createElement("div");
divquest.id = "us_pytanie_" + n;
divquest.innerHTML = "<div class=\"form-group\"> <hr>" + label_pyt.outerHTML
+ "<div class=\"col-md-4\"> " + textarea.outerHTML
+ "</div></div>" + "<div class=\"form-group\">"
+ label_odp_a.outerHTML + "<div class=\"col-md-4\">"
+ input_odp_a.outerHTML
+ "</div></div>"
+ "<div class=\"form-group\">"
+ label_odp_b.outerHTML
+ "<div class=\"col-md-4\">"
+ input_odp_b.outerHTML
+ "</div></div>"
+ "<div id=\"radiodown" + n + "\" ></div>"
+ "<div class=\"form-group\">"
+ "<label class=\"col-md-4 control-label\"> </label>"
+ "<div class=\"col-md-4\">"
+ "<div class=\"btn-group btn-group-justified\">"
+ "<div class=\"btn-group\">"
+ addone.outerHTML
+ "</div>"
+ "<div class=\"btn-group\">"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div>"
+ "</div></div>";
document.getElementById("question").appendChild(divquest);
var btn = document.getElementById("id_" + n);
if (btn.addEventListener) {
btn.addEventListener('click', function() {
add_answer(this);
});
} else if (btn.attachEvent) { // IE < 9 :(
btn.attachEvent('onclick', function() {
add_answer(this);
});
}
n++;
}

abc_index = 0;

function add_answer(index) {
//alert("called"+(this).id);
index = index.id.split("_")[1];
var abc_table_answer = [];
for (var x = 0; x < 20; x++) {
abc_table_answer[x] = ['C', 'D', 'E', 'F'];
}
var abc_table_db_answer = [];
for (var x = 0; x < 20; x++) {
abc_table_db_answer[x] = ['c', 'd', 'e', 'f'];
}
//alert(abc_index + index);
var option = document.createElement("input");
option.id = "odp_" + abc_table_db_answer[index][abc_index] + "_id_" + index + "";
option.name = "data[" + index + "][odp_" + abc_table_db_answer[index][abc_index] + "]";
option.type = "text";
option.className = "form-control input-md";
option.autocomplete = "off";
var label_option = document.createElement("label");
label_option.className = "col-md-4 control-label";
label_option.for = "odp_" + abc_table_db_answer[index][abc_index] + "_id_" + index + "";
label_option.innerHTML = abc_table_answer[index][abc_index] + "";
var optiondiv = document.createElement("div");
optiondiv.id = "us_answer_" + index + "_" + abc_index + "";
optiondiv.className = "form-group";
optiondiv.innerHTML = label_option.outerHTML + "<div class=\"col-md-4\">" + option.outerHTML + "</div></div>";
document.getElementById("radiodown" + index).appendChild(optiondiv);
abc_index++;
}
<input type="submit" value="ADD" onclick="add_question();" />
<br/><br/>
<div id="question"></div><br/>

但是下面的题没有用分表,问题就来了。

请告诉我是否有解决此问题的方法。

预先感谢您的帮助。

编辑

同时添加jsfiddle

jsfiddle DEMO

最佳答案

演示大纲

问题

向列表添加额外答案的 OP 预期行为。

  1. 问题

    一个。回答

    回答

    回答

    回答<--附加到列表

这是实际行为:

  1. 问题

    一个。回答

    回答

    回答

    回答 <-- 附加到列表中,因为问题 1 有 d. answer

因为表单是由用户交互事件(即单击按钮)驱动的,所以循环和数组并不是完全必要的。如果此项目稍后要使用来自动态源的数据,则应考虑数组和循环。

演示大纲

  1. base()函数创建几个基本元素(这是不重复的布局部分),并设置所需的属性。
  2. 所有元素都附加到 documentFragment然后将其附加到 DOM。
  3. 首选#1 和#2 中描述的过程,因为在 DOM 中运行任何内容都需要浏览器做更多工作。
  4. 加载后,布局有一个 <fieldset>左侧和右侧的表单字段是一个 iframe。它的目的是显示提交给测试服务器的数据。 注意:由于 SO 沙箱,此功能不起作用。查看此 PLUNKER一个功能齐全的演示。
  5. 单击绿色的添加 按钮将附加一个QA(问题问题和答案)。
  6. 点击蓝色的 Submit 按钮在 SO Stack Snippet 中没有任何作用。 (见#4)
  7. 标记为 True/False 的复选框将隐藏 4 个答案中的 2 个,以适应 bool 性质的问题。
  8. 加号 + 按钮将向其所属的 QA 添加答案。
  9. 所有携带数据的表单控件字段(<textarea><input>)都有一个唯一的#id 和[name]。

更多细节在演示中评论,引用位于本文末尾

演示(有关功能演示,请参阅 PLUNKER)

<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title></title>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet'>
<style>
#quiz {
display: flex;
}

section {
order: 2
}

textarea {
vertical-align: top;
}

.alpha {
list-style: lower-alpha
}

li {
margin: 0 0 10px 20px
}

.list-group-item-heading {
margin-left: 0
}
/* When True/False checkbox is checked,
|| the following rulesets are invoked
*/

.tf:checked+ol>li:last-of-type,
.tf:checked+ol>li:nth-of-type(3) {
display: none;
}

button,
input[type=submit] {
margin: 0 0 10px 0
}
</style>
</head>

<body>


<script>
var n = 0;
/* Fastest way to use .createElement() and
|| .appendChild() is to create a documentFragment,
|| append all elements to the fragment,
|| set attributes to the elements,
|| then append the documentFragment to the DOM
*/
var base = function(n) {
var frag = document.createDocumentFragment();
var quiz = document.createElement('form');
var sec = document.createElement('section');
var btn = document.createElement('button');
var sbt = document.createElement('input');
var fSet = document.createElement('fieldset');
var lgd = document.createElement('legend');
var ol = document.createElement('ol');
quiz.id = 'quiz';
quiz.classList.add('container', 'form-group-lg');
quiz.action = 'http://httpbin.org/post';
quiz.method = 'post';
quiz.target = 'view';
sec.className = 'col-md-6';
btn.id = 'add0';
btn.type = 'button';
btn.classList.add('btn', 'btn-primary', 'pull-right');
sbt.type = 'submit';
sbt.classList.add('btn', 'btn-success', 'pull-right');
btn.textContent = 'Add';
fSet.id = 'set0';
fSet.classList.add("form-group", "col-md-6");
lgd.textContent = "Quiz Template";
ol.id = 'qa0';
ol.className = 'list-group';
frag.appendChild(quiz);
quiz.appendChild(sec);
fSet.appendChild(sbt);
fSet.appendChild(btn);
quiz.appendChild(fSet);
fSet.appendChild(lgd);
fSet.appendChild(ol);
document.body.appendChild(frag);
genQA(n, '#qa0');
/* .insertAdjacentHTML() is .innerHTML on
|| steroids.
|| Use this for complex layouts and elements that
|| are heavy with attributes
*/
sec.insertAdjacentHTML('beforeend', "<iframe name='view' src='about:blank' width='100%' height='60%' frameborder='1'></iframe>");
}

var genQA = function(n, sel) {
var dock = document.querySelector(sel);
/* This is an ES6 Template Literal
|| It's a Literal String with a new powerful
|| syntax:
Wrap - LS: in quotes ' or " | TL: wrap in backticks `
Variables - LS: ' + var + ' | TL: ${var}
2+Lines - LS: + or \[enter] | TL: [enter]
*/
var cFields = `
<li class='list-group-item-heading'>
<textarea id='q${n}' name="q${n}" rows='3' cols='25'></textarea>
</li>
<label>True/False</label>&nbsp;&nbsp;<input class='tf checkbox-inline' type='checkbox'>

<ol class='list-group alpha'>
<li>
<input id="a${n}_1" name="a${n}_1" type="text" class="input-md" autocomplete="off">
</li>
<li>
<input id="a${n}_2" name="a${n}_2" type="text" class="input-md" autocomplete="off">
</li>
<li>
<input id="a${n}_3" name="a${n}_3" type="text" class="input-md" autocomplete="off">
</li>
<li>
<input id="a${n}_4" name="a${n}_4" type="text" class="input-md" autocomplete="off">
</li>
</ol>
<label id='a${n}' class='btn btn-info ans'>&#65291;</label>
<hr>
`;

dock.insertAdjacentHTML('beforeend', cFields);

}
// Invoked once per session
base(n);

/* Referencing form and its form control fields
|| using HTMLFormControlsCollection
*/
var form = document.forms[0];
var field = form.elements;

/* Register the click event on button#add0
|| invoke addQA() callback function
*/
field.add0.addEventListener('click', addQA);

/* Simple callback to generate a QA and
|| increment counter
*/
function addQA(e) {
n++;
genQA(n, '#qa0');
}

/* Register the click event on fieldset#set0
|| invoke the callback function addA()
*/
field.set0.addEventListener('click', addA);

function addA(e) {
// if the node clicked has the .class '.ans'...
if (e.target.classList.contains('ans')) {
// Reference e.target by #id
var tgt = document.getElementById(e.target.id);
// Get the main index (the number in its #id)
var idx = parseInt(e.target.id.substring(1), 10);
// Find the <ol> sibling preceding it (older bro)
var list = tgt.previousElementSibling;
/* Get the #id of the <ol>'s child's child
|| element (grandkid)
*/
var last = list.lastElementChild.lastElementChild.id;
// Get the last digit of its #id and increment it
var jdx = parseInt(last.split('_').pop(), 10) + 1;
/* This is a Template Literal of a list item and
|| input with interpolated #id and [name]
*/
var li = `<li><input id="a${idx}_${jdx}" name="a${idx}_${jdx}" type="text" class="input-md" autocomplete="off"></li>`;
// Append new list item to list
list.insertAdjacentHTML('beforeend', li);
}
return false;
}
</script>
</body>

</html>

引用资料

关于使用 DOM 和 appendChild 的函数中的 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46631485/

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