【问题标题】:jQuery function parameter passingjQuery函数参数传递
【发布时间】:2011-06-17 12:31:32
【问题描述】:

我尝试在 jquery 中调用一个带有参数的函数

$(document).ready( function() {
    $('#id_pros').bind('change', wordCounter('id_pros_wordCountLabel') );
});

function wordCounter(item){
    ....
}

如果我不传递参数id_pros_wordCountLabel 它工作得很好,但现在它没有调用 wordCounter。

我的代码哪部分有问题?

谢谢

【问题讨论】:

  • Bind 要求您传递对函数的引用(或直接传递匿名函数),但您在“绑定”过程中执行该函数,该过程返回未定义,因此没有任何绑定。跨度>

标签: jquery function parameter-passing


【解决方案1】:

.bind() 需要一个函数参数,如下所示:

$('#id_pros').bind('change', wordCounter);

注意wordCounter 上没有括号。这意味着它是对函数的引用,而不是对函数的调用——当你添加括号时会发生这种情况。使用匿名函数解决问题:

$('#id_pros').change(function ()
{
    wordCounter('id_pros_wordCountLabel');
});

(我还将.bind('change', ...) 更改为.change(...),这等效但更简洁。)

【讨论】:

    【解决方案2】:

    正确的做法是:

    $(document).ready( function() {
        $('#id_pros').bind('change', function() {
            wordCounter('id_pros_wordCountLabel');
        });
    });
    

    您自己的代码将wordCounter(当场调用,而不是在change 事件触发时调用)的返回值传递给bindbind 期望接收一个函数,而wordCounter 可能会返回其他内容,因此当change 事件触发时,您不会看到任何事情发生。

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 2010-09-27
      • 1970-01-01
      • 2011-04-16
      • 2017-02-05
      • 2014-10-18
      • 1970-01-01
      • 2013-09-25
      • 2011-08-26
      相关资源
      最近更新 更多