gpt4 book ai didi

javascript - 从回调函数访问数据

转载 作者:行者123 更新时间:2023-12-02 14:16:31 25 4
gpt4 key购买 nike

  let toggleForm = function() {
// code here
}

document.getElementById('one').addEventListener("click", toggleForm, false);

document.getElementById('two').addEventListener("click", toggleForm, false);

在toggleForm中,我想知道元素一还是元素二触发了事件。你会怎样做呢?

最佳答案

使用e.target:

<button id = 'one'>One</button>
<button id = 'two'>Two</button>
<script>
var one = document.getElementById('one'),
two = document.getElementById('two');
let toggleForm = function(e) {
if (e.target === one) alert('One');
else alert('Two');
};
one.addEventListener("click", toggleForm, false);
two.addEventListener("click", toggleForm, false);
</script>

关于javascript - 从回调函数访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38986146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com