簡體   English   中英

JavaScript 多次調用相同的函數名

[英]JavaScript call same function name multiple times

我有一個函數,我想多次調用它,該函數會生成一個按鈕,但是如果我多次調用它,它將沒有自己的參數。 我怎樣才能做到我希望每個功能都是獨一無二的?

 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM