1 回答
TA贡献1847条经验 获得超11个赞
当您创建新的输入和输出 div 时,您将对所有输入和输出应用相同的 id。取而代之的是,您可以使用计数器编号“cc”来提供所有唯一 ID。然后,当您调用 parse 函数时,您已经在为其提供参数“this”。使用 'this' 通过 id 获取元素。如果具有此输出 id 的 div 已经存在,只需更改其内容,否则创建一个新的。
<script>
// counts the number of input divs created
function increment() {
increment.n = increment.n || 0;
return ++increment.n;
}
// creates an input div
function CreateInputDiv() {
increment();
cc = increment.n;
//console.log("increment.n = " + cc);
input = document.createElement("div");
input.setAttribute("id", "input"+cc);
input.setAttribute("class", "input");
input.innerHTML = " ";
input.setAttribute("contenteditable", "true");
input.setAttribute("onkeypress", "parse(event, this)");
document.getElementById('calc').appendChild(input);
input.focus();
}
// creates an output div
function CreateOutputDiv() {
output = document.createElement("div");
output.setAttribute("id", "output"+cc);
output.setAttribute("class", "output");
output.setAttribute("tabindex", "0");
output.setAttribute("contenteditable", "true");
document.getElementById('calc').appendChild(output);
}
function parse(e,e2) {
//console.log(e2);
var key = window.event.keyCode;
if (key == 13) { //keycode for enter
event.preventDefault();
//console.log(e2.id);
var inId = e2.id;
var outId = "output"+ inId.substring(5);
//console.log(outId);
var inz = input.innerText;
// check if input contains a colon. Hides output if colon exist.
if (inz.indexOf(':') > -1) {
// colon
var inz = input.innerText.replace(/:/g, '');
//console.log("input without colon = " + inz);
var outz = eval(inz);
//console.log("out = " + outz);
document.getElementById("count").value += '\n' + eval(cc + 1);
CreateInputDiv();
}
else {
// no colon = display output
// counter
if(document.getElementById(outId)) {
console.log("Already created");
inz = document.getElementById(inId).innerText;
console.log(inz);
var outz = eval(inz);
document.getElementById(outId).innerHTML = outz;
}
else {
document.getElementById("count").value += '\n' + '\n' + eval(cc + 1);
// create output div
CreateOutputDiv();
// calculate and assign output value to output div
//console.log("input = " + inz);
var outz = eval(inz);
//console.log("out = " + outz);
output.innerHTML = outz;
// creates a new input div
CreateInputDiv();
}
}
}
}
</script>
添加回答
举报