程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了为动态创建的按钮添加随机函数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决为动态创建的按钮添加随机函数?

开发过程中遇到为动态创建的按钮添加随机函数的问题如何解决?下面主要结合日常开发的经验,给出你关于为动态创建的按钮添加随机函数的解决方法建议,希望对你解决为动态创建的按钮添加随机函数有所启发或帮助;

所以我使用 for 循环动态创建了一些按钮,没什么特别的,但是我需要为每个按钮分配一个函数数组中的随机函数和一个随机样式。怎么办呢?
另外我如何运行按钮,因为

button.addEventListener ("click",actions[i]());

仍然只是执行不在按钮上的功能
我的代码

let i = 1;
let body = document.getElementsByTagname("body")[0];
//Functions
let actions = [add,clear,flow]
//styles color of btn ?
let styles = ["blue","red"]

for (i; i <= 20; i++) {
  let button = document.createElement("button");
  button.INNERHTML = 'button '+i;
  body.appendChild(button);
  //heres where i'm lost
  button.addEventListener ("click",function() {
    alert(this.INNERHTML);
  });
}

解决方法

button.addEventListener ("click",actions[i]());

由于末尾的括号,尝试在您分配函数时调用该函数。设置事件处理程序时,您只需传递对函数的引用(因此无需括号)。

您需要根据数组的长度获取随机数,然后将这些随机数传递到各自的数组中以从中获取值。

请参阅下面的内嵌评论。

// There is only one body,no need to try to find all of them
let body = document.body;

//Functions
function add(){
  console.log("add");
}

function clear(){
  console.log("clear");
}

function flow(){
  console.log("flow");
}

let functions = [add,clear,flow];

// Use the names of predefined classes
let classes = ["blue","red","green","yellow","orange"];

// You should get used to starting to count from 0 because
// that's the first index in JavaScript arrays.
for (let i = 0; i < 20; i++) {
  let button = document.createElement("button");
  // Don't use .innerHTML when you aren't working with HTML
  button.textContent = 'Button '+ (i + 1);
  
  // Get a random number that maps to one of the indexes in the
  // classes array and then get that class out of the array and
  // add it to the element
  button.classList.add(classes[Math.floor(Math.random() * classes.length)]);
  
  body.appendChild(button);
  
  //heres where i'm lost
  // Get a random number that maps to one of the indexes in the 
  // functions array and pick that function to assign
  
  // Get the random number that will be the array index:
  let index = [Math.floor(Math.random() * functions.length)];
  
  // Check to see if that index points to the clear function
  if(functions[index] === clear){
    // If so,add the CSS class that hides it.
    button.classList.add("hidden");
  }
  button.addEventListener ("click",functions[index]);
}
.blue { background-color:skyblue; }
.red { background-color:red; }
.green { background-color:green; }
.yellow { background-color: yellow; }
.orange { background-color: orange; }

.hidden { display:none; }

大佬总结

以上是大佬教程为你收集整理的为动态创建的按钮添加随机函数全部内容,希望文章能够帮你解决为动态创建的按钮添加随机函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: