2015-07-19 63 views
0

我正在使用簡單的聊天腳本,並且需要在按下回車鍵後清除文本字段的方法。按鍵輸入後清除文本字段

我明白了文本字段上的鼠標點擊與onfocus,但按鍵不見了我。還有一種方法可以使用一個命令來使代碼更清潔嗎?

<form onsubmit="chat.sendMsg(); return false;"> 
    <input onfocus="if(this.value !== '') {this.value=''}" onblur="if(this.value == '')" type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" /> 
    <input type="submit" value="Enter" /> 
</form> 

回答

2
<form onsubmit="chat.sendMsg(); this.msg.value = ''; return false;"> 
    <input onfocus="if(this.value !== '') {this.value=''}" onblur="if(this.value == '')" type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" /> 
    <input type="submit" value="Enter" /> 
</form> 

<form onsubmit="chat.sendMsg(); this[0].value = ''; return false;"> 
     <input onfocus="if(this.value !== '') {this.value=''}" onblur="if(this.value == '')" type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" /> 
     <input type="submit" value="Enter" /> 
</form> 
2

首先,使用事件屬性,這些天,過時的不良做法的地步。相反,使用JS來連接你的事件。正如您所標記的使用jQuery的問題,試試這個:

<form> 
    <input type="text" id="msg" name="msg" autofocus="true" placeholder="Type Your Meassage Here" /> 
    <input type="submit" value="Enter" /> 
</form> 
$(function() { 
    $('form').submit(function(e) { 
     e.preventDefault(); 
     chat.sendMsg(); 
     $('#msg').val(''); // clear the message box 
    }); 

    $('#msg').on('focus', function() { 
     this.value = ''; 
    }); 
}); 

注意,我刪除了blur處理程序,因爲它實際上並沒有做任何事情。

+0

...但我甚至不會打擾測試'如果(this.value!=='')' - 如果你要清除它,只是一味地清除它。 –

+0

@StephenP好點,謝謝。更新。 –