我希望仅在单击正确的按钮时才调用指定的函数。
function callback(func){
func();
}
主要功能及其结果:
尝试A:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
});
结果:打开页面并单击任何按钮将运行 function1
尝试 B:
document.addEventListener('click', function () {
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
});
结果:单击页面上的任意位置将运行 function1
尝试 C:
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
结果:打开页面并点击按钮将运行function1并重新加载页面
尝试 D:
document.addEventListener('click', function () {
//The first ID doesn't exist
document.getElementById('imaginaryNum1').addEventListener('click', callback(function1));
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
});
结果:单击页面上的任意位置将运行 function1
尝试 E:
//The first ID doesn't exist
document.getElementById('imaginaryNum1').addEventListener('click', callback(function1));
document.getElementById('num1').addEventListener('click', callback(function1));
document.getElementById('num2').addEventListener('click', callback(function2));
结果:打开页面并点击按钮将运行function1并重新加载页面