问题
In my page head:
<script>
function formula()
{
document.forms["inquire"]["search"].value.scrollIntoView();
}
</script>
In my page body:
<div id="nav">
<form id="inquire" name="inquire" onSubmit="return false;">
Search or inquire here: <input type="text" id="search" name="search" value="<?php search($_GET['search']) ?>" autocomplete="off"/>
<input type="button" name="btnSearch" id="btnSearch" onClick="formula();"/>
</form>
</div>
What I want to happen here is that, when btnSearch is clicked, it activates formula(), taking the value from search in form inquire, and then scrolling to the value in a separate div I have called formula. This works if I put document.getElementById(this.form.search.value).scrollIntoView(); directly into the onClick for btnSearch, however it refuses to work no matter how I set it up as a function. Does anyone here know why it might be doing this, or how I can fix it?
回答1:
It's not working because your function is erroneous:
function formula() {
document.getElementById(document.forms.inquire.search.value).scrollIntoView();
}
That code gets the value of the search field and uses it for an "id" lookup. It'd probably be a good idea to check that there actually is an "id" with the value typed in:
function formula() {
var element = document.getElementById(document.forms.inquire.search.value);
if (element) element.scrollIntoView();
}
来源:https://stackoverflow.com/questions/15619627/javascript-function-will-not-activate-onclick