如何将函数附加到带有参数的事件处理程序

How do I attach a function to an event handler with parameters

本文关键字:参数 事件处理 程序 函数      更新时间:2023-09-26

我正在用jQuery编写,并希望在单击元素时发生一些事情。我想要调用的函数需要参数,并且必须始终监视事件,因此处理程序在$(document).ready()中。我的意思是:

"use strict"
$(document).ready(function(){
    $("<button>").each(
        $(this).click(doSomething)
    );    
});
function doSomething(message){
    alert(message);
}

问题是doSomething需要一个它可以提醒的消息。但是,如果我将代码更改为:

$(document).ready(function(){
    $("<button>").each(
        $(this).click(doSomething("Hello world"))
    );    
});
function doSomething(message){
    alert(message);
}

当页面加载时,"Hello world"会被提醒,点击按钮什么都不会做。我如何保持第一种方式的行为,但传递一个参数的方法?

你需要传递一个匿名函数,然后用所需的参数调用你的函数:

$(document).ready(function(){
    $("button").click(function() {
            doSomething("Hello world!");
        });
    );    
});
function doSomething(message){
    alert(message);
}

请注意,我已经修改了选择器,使其选择现有的<button>元素,而不是创建一个新的,并删除了不必要的.each(),因为.click()隐式迭代匹配的元素已经。

试试这个:

  $("button").click(function(){
        doSomething("Hello world");
    });
    function doSomething(message){
        alert(message);
    }

您需要bind-function。这是最近添加到ECMAScript的,如果它不可用,您需要提供它:

if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
  };
}

查看此页的参考:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

如果你包含了这段代码,你可以做以下的事情:

$(document).ready(function(){
    $("button").click(doSomething.bind("Hello world"));
});
function doSomething(message){
    alert(message);
}

你的代码中有很多错误,首先,$("<button>")创建新的dom元素,而不是选择页面上现有的元素。关于这部分doSomething("Hello world") -您立即评估代码,在Jquery点击引用中,您可以看到数据处理程序必须作为第一个参数。下面是正确的清单

$().ready(function(){
    $("button").each(
        $(this).click("Hello world",doSomething)
    );    
});
function doSomething(message){
    alert(message);
}