【问题标题】:How to call a function on .change()? [duplicate]如何在 .change() 上调用函数? [复制]
【发布时间】:2015-12-21 14:38:01
【问题描述】:

总结:我想在复选框的状态更改时调用外部函数。

以下代码包含调用更改works的函数(代码在JSFiddle,注释部分)

HTML

<input type="checkbox" id="cb">

JS

$("#cb").change(function () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    });

正如预期的那样,选中或取消选中复选框时会引发alert


我现在想move the function part outside the .change() method:

$("#cb").change(alertme());

function alertme () {
        if ($("#cb").prop('checked'))
        {
            alert('checked');
        } else {
            alert('unchecked')
        }
    }

这不再起作用(状态变化没有警报)。为什么会这样?

【问题讨论】:

  • alertme 而不是 alertme()
  • 答案很清楚,谢谢。反对票,嗯,...
  • 你有两种方法:第一种:$("#cb").change(alertme);第二种:$("#cb").change(function() { alertme(); });我更喜欢第二个版本,你需要传递函数的引用,你可以看到或重现一个函数

标签: javascript jquery


【解决方案1】:

你只需要函数定义,不要执行它:

$("#cb").change(alertme);

【讨论】:

    【解决方案2】:

    不执行函数,只是将其作为回调传递:

    $("#cb").change(alertme);
    
    function alertme () {
            if ($("#cb").prop('checked'))
            {
                alert('checked');
            } else {
                alert('unchecked')
            }
        }
    

    【讨论】:

      【解决方案3】:

      您只想将函数名称传递给更改事件,而不是实际调用函数并传递返回值。改用这个:

      $("#cb").change(alertme);
      

      【讨论】:

        猜你喜欢
        • 2017-02-03
        • 1970-01-01
        • 2019-10-19
        • 2015-09-07
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 1970-01-01
        • 2019-03-05
        相关资源
        最近更新 更多