带有复选框的jQuery更改事件处理程序

jQuery change event handler with checkbox

本文关键字:事件处理 程序 jQuery 复选框      更新时间:2024-01-20

我有一个复选框,当它被启用(选中)时,我希望执行代码。它可以工作,但当复选框未选中时,代码仍然可以工作,我希望它在复选框未勾选时不工作。下面的代码在一个更大的jQuery函数中。当我取消选中该框时,我无法使代码停止工作。作为参考,复选框允许用户使用箭头键来调整画布元素。我希望他们能够在复选框被选中时进行调整,而在未选中时无法进行调整。

$("#hMove728").click( function(){
   if($(this).is(':checked')){
    alert("checked");
    $(document).keydown(function(key) {
            switch(parseInt(key.which,10)) {
                case 38:
                    context.yB -= 2;
                break;
                    case 39:
                    x += 2;
            break;
            case 40:
                y += 2;
            break;
            case 37:
                x -= 2;
            break;
            default:
            break;
       }
     update();
    })
   }
});

在这里,检查事件处理程序中复选框的状态:

var moveCheckbox = $("#hMove728");
$( document ).keydown( function( key ) {
  if ( moveCheckbox.is(":checked") ) {
    // ...
  }
});
$(function () {
    $('input').on('change', function () {
        if ($(this).prop('checked')) {
            // It is checked
        }
    });
});

在else中放入:$(document).unbind('keydown');

这将解除对document元素上具有keydown名称的事件的绑定。

当您删除检查时,您必须在文档上"注销"keydown"事件,或者您可以在keydown函数中进行检查。像这样:

$(document).keydown(function(key) {
    if(!$("#hMove728").is(':checked')) return;
    switch(parseInt(key.which,10)) {
        case 38:
            context.yB -= 2;
        break;
            case 39:
            x += 2;
        break;
        case 40:
            y += 2;
        break;
        case 37:
            x -= 2;
        break;
        default:
        break;
   }
   update();
});