2014-03-30 93 views
0

內引導模態窗口我有這一塊的html:的Javascript按鍵輸入無法識別

<form class="form-inline" role="form"> 
     <button type="button" class="btn btn-training-comment btn-lg"> 
     <a href="#"> <img src="/img/training-icon-large.png" alt="icon" width="35" height="24"></a> 
     </button> 

    <div class="form-group training-comment-form-wrapper"> 
     <label class="sr-only" for="commentInput">Enter comment..</label> 
      <input type="text" class="form-control training-comment" id="commentInput" placeholder="Enter comment"> 
     </div> 
    </form> 

而且我有這樣的Javascript代碼:

$("#commentInput").onkeypress = function (e) { 
    if (!e) e = window.event; 
    var keyCode = e.keyCode || e.which; 
    if (keyCode == '13') { 
     console.log("clicked"); 
     addComment(); 
    } 
}; 

但我的回車鍵按下不捕獲和「點擊」不會被記錄。這是爲什麼發生?

回答

0

我更新了您的onkeypress以使用.on()並刪除了一些其他不必要的事情。你也在比較一個數字和一個字符串。 keyCode =='13'。希望這可以幫助。

$(document).ready(function(){ 
    $(document).on('keypress','#commentInput', function (e) { 
     console.log('Keyboard Key Number: '+e.which); 
     if (e.which == 13) { 
      e.preventDefault(); 
      console.log('enter was pressed. '); 
     } 
    }); 
}); 

此外,您應該刪除嵌套在中的錨標記。這是沒有必要的。

<button type="button" class="btn btn-training-comment btn-lg"> 
    <a href="#"> <img src="/img/training-icon-large.png" alt="icon" width="35" height="24"></a> 
    </button> 

這裏是工作提琴:http://jsfiddle.net/FVK7f/ - (使用您的標記)與周圍形式的額外包裝股利。

編輯:更改事件綁定以使用文檔。

+0

謝謝,但還是一無所獲:( – hyperN

+0

你在哪兒包括jQuery的? – xCNPx

+0

這不是與jQuery的問題,我已經包括了這其中呼籲模式頁上,當這次沒工作我已經將它包含在模態模板中,以確保 – hyperN

0

使用

$("#commentInput").keypress(function (e) { 

代替

$("#commentInput").onkeypress = function (e) { 

if (keyCode == '13') { 

引號是沒有必要的。

+0

感謝的答案,但它din't幫助 – hyperN