Javascript :: textarea中的新行

时间:2014-05-07 08:22:14

标签: javascript

在我的HTML文件中,我有这段代码:

<textarea class="form-control" id="textfield" rows="10"></textarea>

在我的Javascript文件中,我有这个:

    input1 = document.getElementById('input1').value;
    input2 = document.getElementById('input2').value;
    textfield = document.getElementById('textfield');

    if(document.getElementById('tmkbSelect').value == "option1") {
        document.getElementById('tmkb').innerHTML = "Tafel";
        for(input2i=0;input2i<20;input2i++){
            document.getElementById('textfield').value = input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i;
        }
    }

我基本上试图创建一个乘法表。它有效,但并不完全。

javascript代码在函数中,我使用按钮调用该函数,但问题是输出是这样的:

3 * 19 = 57

我希望它是:

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

依此类推,我该怎么做? 我只需要使用Javascript即可。

3 个答案:

答案 0 :(得分:1)

您需要连接字符串,然后将它们放在textarea中。

您可以将字符串添加到数组中,然后在循环之后将它们连接起来并将它们放在textarea中:

var lines = [];
for(input2i=0;input2i<20;input2i++){
  lines.push(input1+" "+"*"+" "+input2i+" "+"="+" "+input1*input2i);
}
document.getElementById('textfield').value = lines.join('\n');

答案 1 :(得分:1)

使用 ShortHand 运算符将内容添加到textarea。

document.getElementById("test").value += "\n 1";

Demo

答案 2 :(得分:0)

在循环中,您可以指定值:

... .value = input1+...

这意味着您每次都会覆盖内容。你需要追加:

var content = '';
...
content += input1+...
...
document.getElementById('textfield').value = content;

请注意+=

不要忘记在每行之后添加'\n'或一切都在一行。

相关问题