将点击的元素传递给函数

Passing the clicked element to a function

按钮 2 没有按预期工作(像按钮 1 一样更新它的文本)。 “this”不是指按钮元素,而是指 window。如何修复按钮 2?谢谢

<button id="btn1">Click me 1</button>
<button id="btn2">Click me 2</button>

<script>
  var btn1 = document.getElementById("btn1");
  var btn2 = document.getElementById("btn2");

  btn1.addEventListener("click", function() {
    this.innerText = "Come on";
  });


  btn2.addEventListener("click", changeMyText(this));

  function changeMyText(btn) {
    btn.innerText = "Come on";
   // console.log(btn);
    //here I get the window object
    //I expected the button
  }
</script>

您立即执行处理程序 - 删除 (this) 并使用 e.target

另外我会改成 type="button"

<button type="button" id="btn1">Click me 1</button>
<button type="button" id="btn2">Click me 2</button>

<script>
  var btn1 = document.getElementById("btn1");
  var btn2 = document.getElementById("btn2");

  btn1.addEventListener("click", function() {
    this.innerText = "Come on";
  });


  btn2.addEventListener("click", changeMyText);

  function changeMyText(e) {
    e.target.innerText = "Come on";
  }
</script>