我编写了一个函数search,希望单击链接时会调用该函数,如下面的代码片段所示:
<script>
function search() {
console.log('Searching');
}
</script>
<a href="#" onclick="search();">Click here</a>Run Code Online (Sandbox Code Playgroud)
但是,该代码无法按我预期的方式工作,当单击链接时会导致此错误(在Chrome中):
未捕获的TypeError:搜索不是函数
我尝试记录日志search以查看为什么引发了错误:
<a href="#" onclick="console.log(search)">Click here</a>
Run Code Online (Sandbox Code Playgroud)
<a href="#" onclick="console.log(search)">Click here</a>
Run Code Online (Sandbox Code Playgroud)
这次,每次单击链接时,控制台都会记录一个空字符串。令我感到困惑的是,search实际上它在其他地方定义为空字符串,这使我的函数定义毫无用处。
所以我想知道单击事件被触发时发生什么情况,以及何时search定义?