var season = "10";
$( document ).ready(function() {
$("#table").hide();
});
$('#searchButton').on("click", showTable(event));
function showTable(event){
$("#table").show();
document.getElementById("td").innerHTML = season;
}
showTable(event) 函数怎么可能在页面加载时自动执行?
另一个问题是,如果单击按钮,单击事件将不起作用。
我做错了什么?
How is it possible, that the function showTable(event) is automatically executed when the page is loaded?
因为您正在调用函数:showTable(event)
。函数引用后的()
表示执行该函数。您正在调用 showTable
并将返回值(undefined
)传递给 .on()
。
这是一个简化的例子:
function foo() {
return 42;
}
function bar(x) {
console.log(x);
}
bar(foo());
这会调用函数 foo
,并将其返回值 (42
) 传递给 bar
,后者又会记录该值。
如果我们改为编写 bar(foo)
,我们将传递函数本身,而 bar
可以执行该函数。
What did I do wrong?
您正在调用 函数。将它传递给 .on
并让浏览器调用它:
$('#searchButton').on("click", showTable);