jQuery使用参数绑定和取消绑定事件

Pau*_*opf 8 jquery bind unbind

我试图将事件绑定到textbox包含参数的事件.以下看起来好像应该这样做,但每次页面加载时,它都会被执行.

jQuery(function(){
    jQuery('#textbox').bind('click', EventWithParam('param'));
});
Run Code Online (Sandbox Code Playgroud)

每次页面加载时都会使用该参数调用该事件.这可能不起作用,因为不支持带参数的事件.如果是这样,还有另一条路线吗?

jso*_*onx 11

您可以将事件参数作为第二个参数传递给bind().它不是直接的回调参数,但也许你想使用它:

从jQuery文档: bind

function handler(event) {
    alert(event.data.foo);
}  
$("p").bind("click", {foo: "bar"}, handler)
Run Code Online (Sandbox Code Playgroud)


bdu*_*kes 10

要绑定带参数的函数,请使用匿名函数作为参数的闭包.

jQuery(function($) {
    var param = 'text';
    $('#textbox').click(function() {
        EventWithParam(param);
        // or just use it without calling out to another function
        $(this).text(param);
    });
});
Run Code Online (Sandbox Code Playgroud)

您的示例是执行该EventWithParam函数,然后尝试绑定到该函数调用的结果.

unbind不指定函数的情况下调用将取消绑定指定类型的事件(包括匿名函数)的所有处理程序.如果你想专门取消绑定该功能,你需要为它提供一个名称,如下所示:

jQuery(function($) {
    var param = 'text',
        clickCallback = function() {
            EventWithParam(param);
            // or just use it without calling out to another function
            $(this).text(param);
        };
    $('#textbox').click(clickCallback);
});
Run Code Online (Sandbox Code Playgroud)