2010-06-13 63 views
1
<textarea onfocus=" javascript:clearContents(this); this.cleared=true;" rows="5" cols="40" id="comment" name="comment" <?php if($vis["username"] == $pusername) { echo "DISABLED"; } ?>>...</textarea> 
<input onsubmit="if (!this.comment.cleared) clearContents(this.comment); return true;" type="submit" name="Submit" value="Stem!"/> 

function clearContents(element) { 
    element.innerHTML = ''; 
} 

這不會工作,我不知道爲什麼。它的作用:清除,如果它未得到的onfocus /點擊廣告的人的內容Javascript onsubmit clearcontent not working

回答

1
clearContents(document.getElementById('comment')) 

你應該綁定onsubmit<form>併爲此悄悄地,理想......

1
<input onsubmit="if (!this.comment.cleared) 

this<input>。輸入元素沒有submit事件或comment屬性。也許你希望把這個周邊<form>元素:

<form onsubmit="if (!this.comment.cleared) ... 

雖然有可能把它的提交按鈕,你不得不使用​​,高達導航的形式和下至其他輸入。將表單提交代碼綁定到特定的按鈕通常不是一個好主意。

正如meder所說,在內聯事件處理程序中執行所有這些操作有點難看。 (尤其是不必要的javascript:前綴。)更喜歡從JS分配,而不是:

<form id="someform" method="post" action="somewhere"><div> 
    <textarea 
     rows="5" cols="40" name="comment" 
     <?php if($vis['username']==$pusername) { ?>disabled="disabled"<?php } ?> 
    > 
     ... 
    </textarea> 
    <input type="submit" name="Submit" value="Stem!" /> 
</div></form> 

<script type="text/javascript"> 
    var f= document.getElementById('someform'); 
    var cleared= false; 
    f.elements.comment.onfocus= function() { 
     f.comment.value= ''; 
     cleared= true; 
    }; 
    f.onsubmit= function() { 
     if (!cleared) 
      f.comment.value= ''; 
    }; 
</script> 

我已經使用XHTML語法殘疾人屬性(因爲你似乎可以用XHTML語法其它地方),並用value清除內容。不要使用innerHTML-它不會做你的想法,除非它巧合地由於瀏覽器錯誤。應始終使用value訪問表單字段。