如何在复选框更改之前执行功能?

时间:2017-02-13 03:50:04

标签: javascript jquery checkbox mouseevent

我在复选框输入上管理事件侦听器的顺序时遇到了困难。

例如,如果我有这些输入:

<input type='checkbox' class='multi' name='product' id='type1'>
<input type='checkbox' class='multi' name='product' id='type2'>
<input type='checkbox'               name='product' id='type3'>

每当有人点击class = .multi的输入时,我都想听,然后按顺序执行两个函数。

具体来说,我希望function(a)执行,之前注册复选框状态更改(即执行检查之前)。

现在,我有以下系统无法正常工作,因为change事件在启动对话框时触发。我似乎无法暂停change事件,等到:

$('.multi').on('mousedown', function(a){ // open a jqueryUi dialog box and wait to complete function(a)
//do function(a) ...
$('.dialog').dialog('close');

then, once the dialog is closed...

 $(input:checkbox).on('change', function(b){ //do function b only after function a has completed

3 个答案:

答案 0 :(得分:0)

也许这就是你要找的东西:(尚未测试过,但这就是我的想法)

$('.multi').on('click',function(e) {
    e.preventDefault();
    function(a); // your function
    $(this).trigger('click');
});
祝你好运^^

更新

抱歉,上面的代码似乎会进行无限递归,试试这个:

$('.multi').on('click',function(e) {
    e.preventDefault();
    function(a); // your function
    if ($(this).is(':checked')) {
        $(this).prop('checked',false);
    } else {
        $(this).prop('checked',true);
    }
});

答案 1 :(得分:0)

我认为你的流程应该是这样的:

  1. 复选框更改事件
  2. 打开对话框(模态)
  3. 对话框(打开回调)调用函数a)
  4. dialog(close callback)调用函数b)
  5. e.g

    定义对话框

     var dlgOptions={
         title:'My dialog',
         modal:true,
         buttons:{..},
         open:function(event, ui){
           //invoke function a
         },
         close:function(event, ui){
           //invoke function b
         }
        }
    

    然后

    $('.multi').on('change',function(e) {   
        $("#dlgSelector").dialog(dlgOptions)
    });
    

答案 2 :(得分:0)

这就是我要做的。

function functionB() {
    // Whatever you want to do here
}

// Initialise the dialog, specifying functionB as your callback function
// which will run automatically when the dialog closes.
$('.dialog').dialog({
    close: functionB
});

// Handle mousedown for any checkbox with 'multi' class
$('.multi').on('mousedown', function(a){
    // Do stuff...
    $('.dialog').dialog('close');
});

// Handle the 'change' event for any checkbox that DOESN'T have the 'multi' class
$(input:checkbox).not('.multi').on('change', functionB);

这种方式当您选中带有'multi'类的复选框时,它会完成它的操作,然后关闭对话框。然后,因为我们告诉对话框每当它关闭时调用functionB,functionB就会执行。

另一个没有'multi'类的复选框仍然可以在'change'事件中独立调用functionB。