简体   繁体   English

Javascript :: textarea中的新行

[英]Javascript :: New lines in textarea

In my HTML file I have this snippet of code: 在我的HTML文件中,我有以下代码片段:

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

And in my Javascript file I have this: 在我的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;
        }
    }

I'm basically trying to create a multiplication table. 我基本上试图创建一个乘法表。 It works, but not quite. 它有效但不完全。

The javascript code is in a function and I call that function using a button, but the problem is that the output is this: javascript代码在一个函数中,我使用一个按钮调用该函数,但问题是输出是这样的:

3 * 19 = 57

I want it to be: 我希望它是:

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

And so on, how do I do this? 等等,我该怎么做? I need to do this using only Javascript. 我只需要使用Javascript就可以做到这一点。

You need to concatenate the strings and then put them in the textarea. 您需要连接字符串,然后将它们放在textarea中。

You can add the strings to an array, and then concatenate them after the loop and put them in the textarea: 您可以将字符串添加到数组中,然后在循环之后将它们连接起来并将它们放在textarea中:

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

Use ShortHand operator for adding content to textarea. 使用ShortHand运算符将内容添加到textarea。

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

Demo 演示

In the loop, you assign the value: 在循环中,您分配值:

... .value = input1+...

That means you overwrite the content every time. 这意味着您每次都会覆盖内容。 You need to append instead: 你需要追加:

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

Note the += . 注意+=

Don't forget to add '\\n' after each line or everything will be in one line. 不要忘记在每一行后添加'\\n' ,否则一切都会在一行中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM