2013-01-21 21 views
1

可能重複:
jQuery keypress() event not firing?如何運行的按鍵事件功能

我使用WordPress作爲我的CMS

而且我也發民投票系統

這是我的jquery的投票功能

如何在按鍵事件上運行此功能?

例如,如果有人按鍵,「A」,此功能將自動運行

我做了谷歌爲atleast半小時,但沒有找到任何相關的結果

<script type="text/javascript"> 
/* <![CDATA[ */ 
(function($) { 
function setCookie(name,value,days) { 
if (days) { 
    var date = new Date(); 
    date.setTime(date.getTime()+(days*24*60*60*1000)); 
    var expires = "; expires="+date.toGMTString(); 
} 
else var expires = ""; 
document.cookie = name+"="+value+expires+"; path=/"; 
} 

function getCookie(name) { 
var nameEQ = name + "="; 
var ca = document.cookie.split(';'); 
for(var i=0;i < ca.length;i++) { 
    var c = ca[i]; 
    while (c.charAt(0)==' ') c = c.substring(1,c.length); 
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); 
} 
return null; 
} 

$(document).ready(function(){ 
$("body").on('click', '.vote-btn:not(.disabled)', function() { 
var el = $(this), 
    nonce = $("input#voting_nonce", el.parent()).val(), 
    id = el.attr('id').replace(/vote-/, ''); // get the Post ID 

el.html('<span id="loader"></span>'); 
var data = { 
    action: 'add_votes_options', 
    nonce: nonce, 
    postid: id, 
    ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'    
}; 
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data, 
function(response){ 
console.log(response); 

    if(response!="-1") { 

el.html('<img src="<?php get_bloginfo('url'); ?>/wp- content/themes/9GAG/happysimily.png">').unbind('click').addClass('clickedyellow'); 
$('.vote-btn', el.closest('div')).addClass('disabled'); 
$("#vote", el.closest('article')).addClass('clickedlove'); 



     if(response=="null") { 
      alert("A vote has already been registered to this IP address."); 

     } else { 
      $("#votecounter", el.closest('article')).html(response); 


     } 
     var cookie = getCookie("better_votes"); 
     if(!cookie) { 
      var newcookie = id; 
     } else { 
      var newcookie = cookie + "," + id; 
     } 
     setCookie("better_votes", newcookie, 0); 
    } else { 
     alert("There was a problem registering your vote. Please try again later or enable browser cookies."); 
    } 

}); 

return false; 
}); 

}) 
})(jQuery); 




/* ]]> */ 
</script> 
+0

看看這個[jQuery的按鍵()事件不觸發?(http://stackoverflow.com/questions/492865/jquery-keypress-event-not-firing?rq=1)對於初學者 – peterm

回答

2

您可以用不同的方式捕捉按鍵,簡單的一種是使用jQuery默認的,

.keypress()

因此,您需要將函數塊設置爲函數名稱。這應該在你的文檔就緒函數中,因爲你的投票功能不是全局的,並且只在準備就緒的情況下。

(function($) { 

    var yourVotingFn = function(){ 
      .........//your code logic 
    } 

    $(body).keypress(function(event) { 
    if (event.which == 13) {//Enter key 
     yourVotingFn(); 
    } 
    }); 

}); 
3

需要添加一個事件偵聽器按鍵(或KEYUP,KEYDOWN等)

$(document).keypress(function(e) { 
if (e.keyCode == 65) {    // "A" key 
    //code.... 
} 
});