我一直在尝试制作一个简单的脚本,但我卡住了。它应该像这样工作:
用户点击 ADD button
添加用于创建问题的字段,之后,用户可以单击ADD ONE OPTION button
, 以便在问题下方创建额外的空白文本区域。
它不起作用。即使我让一个 ADD 按钮工作,但不知何故,另一个按钮停止了,我得到了类似无法调用 null 的“appendChild”方法。
这是代码:
HTML:
<input type="submit" value="ADD" onclick="addquestion();" />
<br/><br/>
<div id="below"></div><br/>
JavaScript:
n=1;
function addquestion() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var addone = document.createElement("input");
addone.type = "button";
addone.value = "Add one option";
addone.onclick = "insertbelow("+n+")";
var div = document.createElement("div");
div.innerHTML = n + ". Question: <br />" + textarea.outerHTML + "<br />" + addone.outerHTML + "<br /><div id=\"radiodown"+n+"\" ></div><hr/><br/>";
document.getElementById("below").appendChild(div);
n++;
}
function insertbelow(index) {
var option = document.createElement("textarea");
option.name = "rad["+index+"]";
var optiondiv = document.createElement("div");
optiondiv.innerHTML = option.outerHTML + "<br/>";
document.getElementById("radiodown"+index).appendChild(optiondiv);
}
最佳答案
这里是 fiddle 检查它的工作正常。
更新:Javascript
n=1;
function addquestion() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var addone = document.createElement("input");
addone.type = "button";
addone.value = "Add one option";
addone.id="id_"+n;
var div = document.createElement("div");
div.innerHTML = n + ". Question: <br />" + textarea.outerHTML + "<br />" + addone.outerHTML + "<br /><div id=\"radiodown"+n+"\" ></div><hr/><br/>";
document.getElementById("below").appendChild(div);
var btn=document.getElementById("id_"+n);
if(btn.addEventListener){
btn.addEventListener('click', function() { insertbelow(this)});
} else if(btn.attachEvent){ // IE < 9 :(
btn.attachEvent('onclick', function() { insertbelow(this)});
}
n++;
}
function insertbelow(index) {
index=index.id.split("_")[1];
var option = document.createElement("textarea");
option.name = "rad["+index+"]";
var optiondiv = document.createElement("div");
optiondiv.innerHTML = option.outerHTML + "<br/>";
document.getElementById("radiodown"+index).appendChild(optiondiv);
}
关于使用 DOM 和 appendChild 的 JavaScript 按钮 onclick 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808657/