jQuery绑定和取消绑定事件与参数 [英] jQuery bind and unbind event with parameters

查看:70
本文介绍了jQuery绑定和取消绑定事件与参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将事件绑定到包含参数的文本框.下面的keep看起来好像应该这样做,但是每次页面加载时,它都会被执行.

I am trying to bind an event to a textbox that contains parameters. The following keep looks as if it should do it, but every time the page loads, it gets executed.

jQuery(function(){
    jQuery('#textbox').bind('click', EventWithParam('param'));
});

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

The event gets called with that parameter every time the page loads. This may not work because events with parameters are not supported. If so, is there another route?

推荐答案

要绑定带有参数的函数,请使用匿名函数充当参数的闭包.

To bind a function that takes parameters, use an anonymous function to act as a closure over the parameters.

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

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

Your example is executing the EventWithParam function, and then trying to bind to the result of that function call.

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

Calling unbind without specifying a function will unbind all handlers for the specified type of event (including the anonymous function). If you want to unbind that function specifically, you'll need to provide it with a name, like this:

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);
});

这篇关于jQuery绑定和取消绑定事件与参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆