如何将函数作为jQuery插件的参数传递

时间:2011-12-14 02:03:36

标签: jquery jquery-plugins

我正在尝试编写一个简单的jQuery插件来显示一个警告框(自定义html + css),并将yes和no按钮绑定到作为插件调用参数传递的函数。

到目前为止,这是我的代码:

(function($) {
$.fn.triggerAlert = function (msg,yes,no) {
    $('#alert_mask').find("span:first").html(msg);
    $('#alert_mask').toggle();

    $('#alert_mask #alert_yes').click(function (yes) {
        if (typeof yes == 'function') { 
            yes($(this));
        }
        $('#alert_mask').hide();
        return false;       
    });

    $('#alert_mask #alert_no').click(function (no) {
        if (typeof no == 'function') { 
            no($(this));
        }
        $('#alert_mask').hide();
        return false;       
    });

}   
})(jQuery);

这是正确的轨道还是完全错误?

谢谢

更新:在Logan F. Smyth回答之后我不得不进行调整,因为这里的yes和no按钮的点击事件被定义了好几次。对于将来的参考或其他人的好处,这里是完整的插件。

(function($) {
  $.fn.triggerAlert = function (trigger,msg,yes,no) {
    var mask = $('#alert_mask');
    $(trigger).click(function (e) {
        mask.find("span:first").html(msg);
        mask.toggle();
        e.preventDefault();
    });

    $('#alert_yes').click(function (e) {
      if (yes) yes($(this));
      mask.hide();
      e.preventDefault(); 
    });
    $('#alert_no').click(function (e) {
      if (no) no($(this));
      mask.hide();
      e.preventDefault();
    });
  }   
})(jQuery);

如何调用它的一个例子

 $().triggerAlert(
    $('#some_element'),
    'hello world',
    function() { alert('yes') },
    function() { alert('no')  }
  );

2 个答案:

答案 0 :(得分:2)

我看到的主要问题是你的点击处理程序采用'no'和'yes'参数,这意味着在这些函数内部,yes和no将不会传递给整个插件。

让你的选择使用两个ID也是不必要的,因为无论如何,id都是唯一的。最后返回false是一个坏主意,改为使用preventDefault。

(function($) {
  $.fn.triggerAlert = function (msg,yes,no) {
    var mask = $('#alert_mask');
    mask.find("span:first").html(msg);
    mask.toggle();

    $('#alert_yes').click(function (e) {
      if (yes) yes($(this));
      mask.hide();
      e.preventDefault(); 
    });
    $('#alert_no').click(function (e) {
      if (no) no($(this));
      mask.hide();
      e.preventDefault();
    });
  }   
})(jQuery);

要触发此操作,您可以调用该函数并传递两个函数,如下所示:

$('#some_element').click(function(e){
  $(this).triggerAlert(
    'hello world',
    function() { alert('yes') },
    function() { alert('no')  }
  );
  e.preventDefault();
})

答案 1 :(得分:0)

参数在函数范围内,你可以这样尝试

  $('#alert_mask #alert_no').click(function() {
    if (typeof no == 'function') { 
        no($(this));
    }
    $('#alert_mask').hide();
    return false;       
});
相关问题