简体   繁体   English

使用.on()将变量传递给函数

[英]Passing variables to function using .on()

I have a text input field with its own class: .my_ids . 我有一个带有自己的类的文本输入字段: .my_ids I'm trying to write a script with jquery so that every time the input changes, it calls a particular function. 我正在尝试使用jquery编写脚本,以便每次输入更改时,它将调用特定函数。 This is easy enough if I don't try to pass a variable to the function: 如果我不尝试将变量传递给函数,这很容易:

$(document).on('change','.my_ids', testfunc);
function testfunc(){
    alert("good");
}

The function sends me an alert every time the input changes; 每当输入更改时,该功能都会向我发送警报; works just fine. 效果很好。

However if I try to pass a variable to the alert function like so: 但是,如果我尝试将变量传递给警报功能,例如:

$(document).on('change','.my_ids', testfunc("hereismyvariable"));
function testfunc(myvariable){
    alert(myvariable);
}

it sends the alert when the document loads and then doesn't alert when the input changes. 它在文档加载时发送警报,然后在输入更改时不发出警报。 What might I be missing? 我可能会缺少什么?

Here you are passing a function: $(document).on('change','.my_ids', testfunc); 在这里,您要传递一个函数: $(document).on('change','.my_ids', testfunc);
Here you are passing the return value of a function: $(document).on('change','.my_ids', testfunc("hereismyvariable")); 在这里,您要传递函数的返回值: $(document).on('change','.my_ids', testfunc("hereismyvariable"));
Because testfunc("hereismyvariable") = undefined (No return value), you add an event handler with an undefined function. 因为testfunc("hereismyvariable") = undefined (没有返回值),所以您添加了一个具有未定义函数的事件处理程序。

You would do this 你会这样做

$(document).on('change','.my_ids', function() {
  testfunc("hereismyvariable");
});

Or you could do this 或者你可以这样做

$(document).on('change','.my_ids', testfunc("hereismyvariable"));

function testfunc(myvariable){
  return function() {
    alert(myvariable);
  }
}

() operator call the functions, so the returned value of the function is set as the handler, which doesn't seem to be what you want. ()运算符调用函数,因此将函数的返回值设置为处理程序,这似乎不是您想要的。 Other answers suggest several solutions. 其他答案提出了几种解决方案。 Another option is using the data argument: 另一种选择是使用data参数:

$(document).on('change', '.my_ids', "hereismyvariable", testfunc);

function testfunc(event) {
    console.log(event.data); // "hereismyvariable"
}

The data argument can be anything. data参数可以是任何东西。 data property of the event object refers to the passed value. event对象的data属性引用传递的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM