问题
I have this very basic code that I feel should be working but isn't.
I have this form:
<form id="search-box" action="">
<input id="search" type="text" placeholder="Search here.." onkeyup="search(this.value)"><!--
--><input id="submit" type="submit" value="Search">
</form>
This form fires a JS search function. This search function contains:
function search(input){
alert(input);
}
I have linked the JS file containing the function in the head of the html document:
<script src="js/ajax.js"></script>
But the problem is this isn't working. I'm getting an error when the onkeyup is fired:
Uncaught TypeError: object is not a function localhost:16:201
onkeyup localhost:16:201
May I get some assitance?
回答1:
In your code, you have a function named search
and an element with the id
of search
. HTML elements with id
's become global variables by that name, so the element with the id
of search
overwrites the search
variable that was your function.
Try something like this.
HTML
form id="search-box" action="">
<input id="search" type="text" placeholder="Search here.." onkeyup="doSearch(this.value)"><!--
--><input id="submit" type="submit" value="Search">
</form>
JS
function doSearch(input){
alert(input);
}
回答2:
In your HTML you can't have an element ID and function names same in a form. These creates conflicts.
When you add a ID in your form it adds that element as form[id]. So if you will have the same names of functions they will create conflict in same form.
Here is a very nice question has been answered about same.
来源:https://stackoverflow.com/questions/24588547/firing-js-function-from-onkeyup-event-input