addEventListener 不适用于默认参数

I_l*_*les 4 html javascript dom

如果我用 调用函数,为什么带有默认参数的函数不起作用addEventListener

这是一个例子:

下面的这个示例函数生成了一些随机字符串,我通过onclick()在 html 文件中使用调用了该函数,它完美地工作

const notationGraph = {
  "U": ["L", "R", "F", "B"],
  "D": ["L", "R", "F", "B"],
  "L": ["U", "D", "F", "B"],
  "R": ["U", "D", "F", "B"],
  "F": ["U", "D", "L", "R"],
  "B": ["U", "D", "L", "R"],
};

const switches = ["", "\'", "2"]; 

function randItem(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function generate3x3(Min = 20, Max = 25) {
  let scrambles = []; 
  let prev;
  const len = Math.floor(Math.random() * (Max - Min + 1) + Min);
  for (let i=0; i<len; i++) {
    let notation = randItem(prev ? notationGraph[prev] : Object.keys(notationGraph));
    let swtch = randItem(switches);
    scrambles.push(`${notation}${swtch}`);
    prev = notation;
  }
  console.log(scrambles.join(" "));
}
Run Code Online (Sandbox Code Playgroud)
<button id="buttonTest" onclick="generate3x3()">test button</button>
Run Code Online (Sandbox Code Playgroud)

但是现在,如果我尝试该addEventListener方法而不是onclick()像下面的代码那样,它就不起作用并且console.log是空字符串

const notationGraph = {
  "U": ["L", "R", "F", "B"],
  "D": ["L", "R", "F", "B"],
  "L": ["U", "D", "F", "B"],
  "R": ["U", "D", "F", "B"],
  "F": ["U", "D", "L", "R"],
  "B": ["U", "D", "L", "R"],
};

const switches = ["", "\'", "2"]; 

function randItem(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}

function generate3x3(Min = 20, Max = 25) {
  let scrambles = []; 
  let prev;
  const len = Math.floor(Math.random() * (Max - Min + 1) + Min);
  for (let i=0; i<len; i++) {
    let notation = randItem(prev ? notationGraph[prev] : Object.keys(notationGraph));
    let swtch = randItem(switches);
    scrambles.push(`${notation}${swtch}`);
    prev = notation;
  }
  console.log(scrambles.join(" "));
}
document.getElementById("buttonTest").addEventListener("click", generate3x3)
Run Code Online (Sandbox Code Playgroud)
<button id="buttonTest">test button</button>
Run Code Online (Sandbox Code Playgroud)

我想知道为什么它不起作用,我做错了什么?

mpl*_*jan 8

因为 eventListener 中传递的事件正在覆盖您的第一个默认参数

将事件作为第一个参数添加到函数中

function generate3x3(event, Min = 20, Max = 25) {
Run Code Online (Sandbox Code Playgroud)

或者这样称呼

document.getElementById("buttonTest").addEventListener("click",function() {
  generate3x3();
})
Run Code Online (Sandbox Code Playgroud)

function generate3x3(event, Min = 20, Max = 25) {
Run Code Online (Sandbox Code Playgroud)
document.getElementById("buttonTest").addEventListener("click",function() {
  generate3x3();
})
Run Code Online (Sandbox Code Playgroud)