I wrote a function named search
that I expected to be called when the link was clicked, as the code snippet below shows:
<script>
function search() {
console.log('Searching');
}
</script>
<a href="#" onclick="search();">Click here</a>
However, the code does not work as I expected, which causes this error (in Chrome) when the link is clicked:
Uncaught TypeError: search is not a function
I tried logging search
to see why the error was thrown:
<a href="#" onclick="console.log(search)">Click here</a>
<script>
function search() {
console.log('Searching');
}
</script>
<a href="#" onclick="console.log(search);">Click here</a>
This time, the console logged an empty string each time the link is clicked. What puzzles me is that search
is actually defined somewhere else as an empty string, making my function definition useless.
So I want to know what happens when a click event is triggered, and when is search
here defined?