在textarea中添加新行

Javascript :: New lines in textarea

本文关键字:新行 添加 textarea      更新时间:2023-09-26

在我的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。

您需要将字符串连接起来,然后将它们放在文本区

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

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

使用 shortcut 操作符向textarea添加内容。

document.getElementById("test").value += "'n 1";
演示

在循环中,赋值:

... .value = input1+...

这意味着您每次都要重写内容。你需要添加:

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

注意+= .

不要忘记在每行后面加上''n',否则所有内容将在一行中