看看文件是否有按键绑定?

时间:2014-03-20 12:59:22

标签: javascript jquery

我正在使用jqlight(similair到jquery,但它没有$ document.data('events'))将按键绑定到文档。

    $document.bind('keypress', function(event){

选中复选框时,我会添加绑定按键,如下所示:

if(onScreenData.getChecked().length > 0){
  $document.bind('keypress', function(event){
else{
  $document.unbind('keypress');
}

其中onScreenData.getChecked().length是复选框的数量。

我想只在复选的复选框数从0开始时绑定按键。

2 个答案:

答案 0 :(得分:3)

为什么要绑定和取消绑定按键事件?更高效的是始终绑定它,但是立即检查事件处理程序中页面上的复选框数量,如果需要,立即返回它。

答案 1 :(得分:2)

你可以随时取消绑定,只在你想要时绑定

$document.unbind('keypress');
if(onScreenData.getChecked().length > 0){
     $document.bind('keypress', function(event){ /* ... */; })
}

您也可以这样做,但这应该被视为一种解决方法:

if( $document.attr('data-has_keypress')=='true'){
    $document.unbind('keypress');
}
if(onScreenData.getChecked().length > 0){
     $document
         .bind('keypress', function(event){ /* ... */; })
         .attr('data-has_keypress', 'true');
}

另外:how to check if element has clickhandler