JavaScript多次调用相同的函数名



我有一个函数,我想多次调用它,函数生成一个按钮,但如果我多次调用它,它将没有自己的参数。怎样才能使每个函数唯一呢?

function(); // I want this to call its own value
function(); // I want this to do something
function(); // I want this to call its own value

我不知道我是否真的理解了你的需要,但是下面的例子向你展示了如何向同一个函数传递不同的参数,并在你想要的情况下多次调用它。

let args = [{
name: 'test',
value: 'value1'
}, {
name: 'test2',
value: 'value2'
}, {
name: 'test3',
value: 'value3'
}];
function test(args) {
if (args) //Check if function has arguments
{
let btn = document.createElement('button'); //create an element type button
btn.innerText = args.name; //Set the created button text
btn.value = args.value; //Set the created button value
//Folowing code add 'EventListener' to catch the user 'click' action
btn.addEventListener('click', function(e) {
console.log('Button clicked with value: ' + this.value) //Log the value of the clicked button to verify if our function is working (set the name and value of generated button)
});
document.body.appendChild(btn); //Append the created button to the DOM
} else {
//Eles do something else
console.log('no arguments passed')
}
};
test() //Function test executed w/o arguments
//Create a loop on args, just for the example
for (i = 0; i < args.length; i++)
test(args[i]) //Funciton test() executed with arguments

一个解决方案是使用多个函数。确保为每个函数提供唯一的名称。

function myFunction(){
console.log('Hello World');
}
function mySecondFunction(){
myFunction();
}
mySecondFunction();

相关内容

  • 没有找到相关文章

最新更新