未捕获的ReferenceError :(函数)未在HTMLButtonElement.onclick中定义 [英] Uncaught ReferenceError: (function) is not defined at HTMLButtonElement.onclick
问题描述
我有一个搜索表单,我试图让它在页面底部输出结果而不重新加载。
I have a search form where I'm trying to have it output the results at the bottom of the page without reloading.
<form action='' method='post'>
<div id="search-form">
<input type="text" name="search" class="search-field" id="search" value="" />
<div class="submit-container">
<button type="button" value="" class="submit" id="searchbutton" onclick="searchoutput()" /></button>
</div>
</form>
<br><br>
<p>Type First Name</p>
我想在点击按钮时使用Ajax调用另一个脚本,在下面显示搜索结果。我一直收到错误:未捕获的ReferenceError:未在HTMLButtonElement.onclick上定义searchoutput
I want the search results to show below when the button is clicked, using Ajax call to another script. I keep getting an error: "Uncaught ReferenceError: searchoutput is not defined at HTMLButtonElement.onclick
这是我的javascript(使用jquery):
Here is my javascript (using jquery):
$( document ).ready(function() {
function searchoutput() {
if($(".search-field").val().length > 5) { //only shows results when more than 5 characters have been entered
var search = $(".search-field").val();
var update = $(".result");
var goal = 0;
$.get("query-include.php" , {search: search, goal: goal})
.done(function( data ) {
update.empty();
update.append(data);
$(this).remove();
});
};
}
$( ".search-field" ).keydown(function() {
var update =$(".results");
update.empty();
});
});
我已检查过其他帖子和花了很长时间试图自己解决问题。奇怪的是,如果我为keyup添加一个事件监听器,以便运行与用户类型相同的函数searchoutput:
I have checked other posts and spent a long time trying to get the solution on my own. The odd thing is if I add an event listener for "keyup" in order to run the same function searchoutput as the user types:
var searchfield = document.getElementById("search");
searchfield.addEventListener("keyup", searchoutput);
然后我没有得到ReferenceError并且脚本运行正常..我只得到函数问题按钮点击。
Then I don't get the ReferenceError and the script runs fine.. I only get the function issue on button click.
推荐答案
这是一个范围问题 - searchOutput
已定义在 $(文档).ready()
函数的范围内。您可以尝试在该代码之前为 searchOutput
声明一个var,然后将其分配给这样的函数:
It's a scoping issue - searchOutput
is defined within the scope of the $(document).ready()
function. What you could try is to declare a var for searchOutput
before that code, then assign it to the function like this:
var searchOutput;
$( document ).ready(function() {
searchOutput = function () {
if($(".search-field").val().length > 5) {
//etc.
这篇关于未捕获的ReferenceError :(函数)未在HTMLButtonElement.onclick中定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!