我想在文本区域(inputbox div)中拆分文本(转换为数组)并在名为result的div id中显示它们?
var txtBox = document.getElementById("inputbox");
var lines = txtBox.value.split("\n");
// print out last line to page
var blk = document.getElementById("result");
blk.innerHTML = lines[lines.length - 1];

<div id="result"></div>
<div id="singleQuote"></div>
<div id="inputbox" style="width: 710px;color: #ffffff;background: activecaption">
On the other hand,
<br/>we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of
</div>
&#13;
答案 0 :(得分:1)
请查看此内容。您需要将value
更改为innerText
。这是因为您正在访问div
而不是input
var txtBox = document.getElementById("inputbox");
var lines = txtBox.innerText.split("\n");
// print out last line to page
var blk = document.getElementById("result");
blk.innerHTML = lines[lines.length - 1];
<div id="result"></div>
<div id="singleQuote"></div>
<div id="inputbox" style="width: 710px;color: #ffffff;background: activecaption">
On the other hand,
<br/>we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of
</div>
答案 1 :(得分:0)
在我看来,您试图分开\n
而不是\n\r
或\r\n
...
另一个奇怪的是,它只适用于innerText
;)
var txtBox = document.getElementById("inputbox");
var lines = txtBox.innerText.split(/[\n\r]/g);
// print out last line to page
var blk = document.getElementById("result");
blk.innerHTML = lines[lines.length - 1];
#result {
background-color: green;
}
#inputbox {
background-color: black;
color: white;
}
<div id="result"></div>
<div id="singleQuote"></div>
<div id="inputbox">
On the other hand,
<br/>we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of
</div>
答案 2 :(得分:0)
使用 split() javascript函数。
例如
str = "abc\ndef";
console.log(str.split("\n"));
将打印出来
["abc", "def"]