2013-07-14 23 views
0

我在HTML下面的代碼:更改HTML textarea的使用JavaScript

<button onclick="showDescription();">Find book</button> 

雖然附加JavaScript文件中:

function showDescription(){ 
    document.getElementById("description").value="book"; 
} 

但是,每當我按一下按鈕,它只顯示字符串「書」1秒鐘,並消失。任何想法出了什麼問題?

回答

0

我猜那個按鈕是一個形式裏面,它改變:

<button onclick="showDescription();">Find book</button> 

到:

<input type="button" onclick="showDescription();" value="Find book" /> 

按鈕具有提交的默認類型,所以它會提交表單如果頁面位於表單元素中,則重新加載頁面。

+1

這是行不通的。事件處理程序仍然沒有返回false。 – Quentin

+0

是的,你是對的!一旦我將該按鈕移出表單,它就會起作用。關於showDescription功能,爲什麼我們會返回false? –

+0

我的不好,你必須在事件處理程序中返回false或更改元素類型或只是更改爲輸入。 – adeneo

1

您的按鈕(大概)在<form>之內。

按鈕的默認類型是submit

  1. JavaScript的運行
  2. 的值更新
  3. 表單提交
  4. 重新加載頁面
  5. 初始值再次顯示

不要使用提交按鈕:

<button type="button" onclick="showDescription();">Find book</button> 

另外,從事件處理函數返回false:

onclick="showDescription(); return false;" 
+0

謝謝!你確實是對的。 –

-1

試試這個代碼:

<!DOCTYPE html> 
<html> 
    <head> 
     <script> 
      function showDescription() 
      { 
       document.getElementById("description").innerHTML="book"; 
      } 
     </script> 
    </head> 
    <body> 

     <button onclick="showDescription();">Find book</button> 

     <textarea id="description" rows="4" cols="50"> 
     </textarea> 

    </body>