2012-03-15 43 views
2

當用戶在文本框中輸入時,我有一個文本框,並點擊輸入它應該提醒該值,並且如果用戶更改值,它也應該警告。所以會有兩個事件按鍵和改變。我想用最少的代碼來調用它。沒有重複的代碼。點擊輸入並更改火災事件

$('#txt').keydown(function (e){ 
    if(e.keyCode == 13){ 
     alert('you pressed enter ^_^'); 
    } 
})​ 

Online Demo

+2

什麼是你的問題?似乎你已經到了那裏。 – 2012-03-15 14:20:03

+0

@Felix我想要按鍵和更改事件。與用戶更改值一樣,點擊外部應該提醒。 – Wazdesign 2012-03-15 14:24:27

+0

然後使用http://api.jquery.com/bind/。 – 2012-03-15 14:30:20

回答

6

可以列出多個事件作爲第一個參數(雖然你仍然必須處理每個事件):

$('#txt').bind('keypress change', function (e){ 
    if(e.type === 'change' || e.keyCode == 13) { 
     alert('you pressed enter ^_^'); 
    } 
})​;​ 

我使用目的綁定,因爲OTS的小提琴使用JQ 1.5 0.2

+0

謝謝這真的是我需要的 – Wazdesign 2012-03-15 15:26:39

1

像這樣的事情?

$('#txt') 
    .keydown(function (e) { 
     if(e.keyCode == 13){ 
      alert('you pressed enter ^_^'); 
     } 
    }) 
    .change(function(e) { 
     alert('you changed the text ^_-'); 
    }); 
1

嘗試live方法:

$("#txt").live({ 
    change: function(e) { 
     alert('you changed the value'); 
    }, 
    keydown: function(e) { 
     if (e.keyCode == 13) { 
      alert('you pressed enter ^_^'); 
     } 
    } 
}); 

http://jsfiddle.net/tThq5/1/

3

這就是我將如何處理這個問題。

http://jsfiddle.net/tThq5/3/

注:我使用$ .live()(V.1.3)而不是$。對()(V1.7),也返回false所以我不明白髮射了1次以上的事件。

$('#txt').live('keypress change', function(e) { 
    if (e.type === 'keypress' && e.keyCode == 13) { 
     alert('you pressed enter'); 
     return false; 
    } else if (e.type === 'change') { 
     alert('you made a change'); 
     return false; 
    } 
});​