0

I'm writing in jQuery and want to make something happen when an element is clicked. The function I want called requires parameters, and the event must be watched for at all times, so the handler is in $(document).ready(). Here's what I mean:

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

The problem is that doSomething needs a message that it can alert. However, were I to change the code to this:

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

Then "Hello world" would be alerted when the page loads, and clicking buttons would do nothing. How do I keep the behavior of the first way, but pass the method a parameter?

4

4 回答 4

3

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

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

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

于 2013-04-26T08:52:27.003 回答
1

试试这个:

  $("button").click(function(){
        doSomething("Hello world");
    });
    function doSomething(message){
        alert(message);
    }
于 2013-04-26T08:51:25.347 回答
0

您需要绑定功能。这是 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);
}
于 2013-04-26T08:51:38.460 回答
-1

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

$().ready(function(){
    $("button").each(
        $(this).click("Hello world",doSomething)
    );    
});
function doSomething(message){
    alert(message);
}
于 2013-04-26T08:57:00.493 回答