【问题标题】:Add random function to dynamically created buttons为动态创建的按钮添加随机功能
【发布时间】:2021-07-08 21:12:32
【问题描述】:

所以我使用 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);
  });
}

【问题讨论】:

  • 你需要传递不带()的函数,如果你传递带有()意味着函数的结果,如果你不带它传递意味着你正在传递函数对象

标签: javascript html arrays button onclick


【解决方案1】:
button.addEventListener ("click", actions[i]());

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

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

请参阅下面的内联 cmets。

// 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; }

【讨论】:

  • 你是圣人!!!!多谢!!!还有一个问题,只有在您有时间的情况下,对于具有 clear 功能的按钮,我将如何定位它并将该特定按钮的可见性删除为无?
  • @MindQ 在分配之前,您将检查哪个函数被选为随机函数,并且很清楚,然后应用一个将可见性设置为无的 CSS 类。我将更新答案以显示这一点。
  • 如果我能无限支持你,我会感谢一百万
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-22
  • 1970-01-01
相关资源
最近更新 更多