2016-11-16 9 views
-2

私のテキスト領域(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>

+1

をプリントアウトします私たちのほとんどは、おそらくあなたの問題を理解することはできません、より冗長にしてください。 –

+0

私はあなたのJSからあなたが新しい行でテキストボックスの内容を分割しようとしていることを伝えることができます。私はこれに2つの問題を見る。 1:あなたやユーザが実際にそこに新しい行を置かない限り、何も分割しません.2:通常は要素が読み込めないことを意味する 'undefined'のプロパティ' split'を読むことができません。値のオブジェクトクラスを確認してください。私が理解しているところから、 'split'は文字列でしか動作しません。 –

+0

doc reference:http://www.w3schools.com/jsref/jsref_split.asp –

答えて

1

、このいずれかを確認してください。 valueinnerTextに変更する必要があります。あなたがあなたの代わりに\n\r\r\n\nに分割しようとしている私の意見では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>

+0

これは私が起こっていたと考えているインラインです。オブジェクトが空のとき分割を使用することはできません:p –

+0

は@KyleLに同意します、それは未定義の場合は分割されません:) – RizkiDPrast

0

にアクセスしているので、それはある... 別の奇妙なことは、それだけで作品です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>

+0

Windowsの改行でHTMLを分割しようとしているのは変ですあなたが 'br'要素で分割しなければならないとき'innerText'には' br'要素はありません。これも標準ではないプロパティで、ほとんどのブラウザではサポートされていません。 – Teemu

0

split() javascript関数。例

str = "abc\ndef"; 
console.log(str.split("\n")); 

については

["abc", "def"]