2012-02-15 29 views
0

的textContent大家好(第一張海報,所以不要拍我...但):的Javascript:基於正文長度

我試圖改變基礎上,一個長度限制:Textlength textarea的。

我的代碼如下:

<script type="text/javascript"> 
      function addComment(){ 
       var commentBank = document.getElementById("commentBank"); 
       var selectedComment = commentBank.options[commentBank.selectedIndex].text; 
       var currentComment = document.getElementById("comment"); 

       console.log(currentComment.textLength); 

       if(currentComment.textContent == "Add comment here"){ 
        currentComment.textContent = selectedComment; 
       }else if(currentComment.textLength == 0){ 
        console.log("Trying to add "+selectedComment); 
        currentComment.textContent = "selectedComment"; 
       } 
       else{ 
       currentComment.textContent += ". " + selectedComment; 
       } 


      } 
      </script> 

我想要做的就是從選項(稱爲commentBank)所選擇的項目,從這個,獲取文本選擇,並將其添加到一個textarea (稱爲評論)。

目前的問題是,currentComment.textContent()等於0時,它不會將文本添加到textarea。 它輸出到日誌,但不會更新textarea添加文本,所以if語句正在工作。

任何想法? 謝謝先進。

回答

0

嘗試使用而不是的textContent,寫一個textarea的內容。

我不知道所有瀏覽器,但在其中一些瀏覽器中,textContent是隻讀的。

0

這是代碼片段你在談論:

 }else if(currentComment.textLength == 0){ 
      console.log("Trying to add "+selectedComment); 
      currentComment.textContent = "selectedComment"; 

的原因,它實際上並沒有添加的評論是因爲你設置currentComment.textContent"selectedComment",而不是。這就是爲什麼它可以在你的日誌中打印出來(因爲你正在記錄這個值)。更改該行:(請注意沒有引號的,它創建與文字值selectedComment字符串)

currentComment.textContent = selectedComment; 

+0

謝謝@Josh,我已經修改了代碼,但無濟於事,我在此之前先玩過它,並且這兩個版本都沒有改變文本。 有沒有其他想法? – TStu 2012-02-15 02:18:18

+0

它似乎按照我的預期工作:http://jsfiddle.net/joshleitzel/9LRN6/基本上你打算髮生什麼? – 2012-02-15 03:18:12

+0

一旦從文本框中刪除文本並選擇一個元素,它將不會添加任何元素。 看來.value正在工作。 感謝您的快速回復 – TStu 2012-02-15 13:08:13