将参数传递给函数I don'我不想立即执行

Passing argument to function I don't want to execute immediately

本文关键字:我不想 执行 参数传递 函数 don      更新时间:2024-01-30

如果我的问题看起来很天真,很抱歉,但我似乎无法得到简单的答案。在JavaScript中,我尝试这样的东西:

window.onload = init; *// ok, this assigns to the window load event a function that doesn't execute straight away*
// now I define my init()function
function init(){
// say...
alert('Noise!');
/* but here is my dilemma... */

接下来说,我想为button.onclick事件分配一个仅在单击按钮时执行的函数。但是(!这里是…!)我想从这里向这个函数传递参数,而不需要执行,因为它(显然)有括号。类似于:

var button = document.getElementById('button');
var promptInput = prompt("Name?");
button.onclick = printName(promtInput); // I only want to print name on button click
}
function printName(name){
alert(name);
}

所以。。。好吧,我知道这个例子很愚蠢。只需移动printName()函数内的所有提示集合,并为button.onclick分配一个无括号的printName函数即可解决问题。我知道。但是,还是。有没有一种方法可以将参数传递给不想立即执行的函数?或者它真的是一条规则(或"根据定义"),当你不打算通过它传递参数时,你只使用等待执行的函数?

否则你该怎么做?

button.onclick = function() {
    printName(promptInput);
};

您可以使用Function.prototype.bind():

bind()方法创建一个新函数,当调用该函数时该关键字设置为提供的值,具有给定的在调用新函数时提供的任何参数之前的参数。

例如:

button.onclick = printName.bind(null, promtInput);

您可以将通常作为参数传递的数据放入其他保存位置。你可以把它放在一个隐藏的HTML元素中,也可以使用sessionStorage API来保存它

var button = document.getElementById('button');
var promptInput = prompt("Name?");
sessionStorage.setItem('MyName', promptInput);
button.onclick = printName; // I only want to print name on button click
}
function printName(){
alert(sessionStorage.getItem('MyName');
}