这是我从建议列表中选择一个时下面的代码,它可以正常工作,但是当我按下搜索按钮时,它不起作用,请帮助!
<script type="text/javascript">
var stream;
function suggest(inputString) {
if (inputString.length == 0 || inputString == " ") {
$('#suggestions').fadeOut();
} else {
stream = inputString;
$('#listings').addClass('load');
$.post("autosuggest.php", { queryString: "" + inputString + "" }, function (data) {
if (data.length > 0) {
$('#suggestions').fadeIn();
$('#suggestionsList').html(data);
$('#listings').removeClass('load');
}
});
}
}
function fill(thisValue) {
$('#listings').val(thisValue);
setTimeout("$('#suggestions').fadeOut();", 100);
stream = thisValue;
}
function go() {
$('#listings').val(stream);
}
</script>
这是 HTML 部分
<div class="search">
<form id="form" action="search_results.php" method="POST" class="new-search">
<div class="field" id="searchform">
<input type="text" size="25" value="" name="search_term" id="listings" onkeyup="suggest(this.value);"
onblur="fill();" class="" />
<button type="submit" name="submit" value="submit" id="search" onclick="go();">
Search</button>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="suggestionsList">
</div>
</div>
</div>
</form>
</div>
当我点击搜索按钮时它不起作用。 POST 方法未传递名称。
带有 id="search"
的按钮是type="submit"
的,并且go()
不会调用preventDefault()
因此单击该按钮会提交表单并在其他代码运行之前重新加载页面
此外,拥抱事件处理程序并从 html 中删除所有 js 调用属性
更新后,您的代码可能如下所示,尽管我无法完全测试它
JavaScript:
<script>
$(function() {
var stream;
var $suggestions=$('#suggestions');
var $listings= $('#listings');
$('#search').click(function(event) {
event.preventDefault()
$('#listings').val(stream);
});
$listings.keyup(function() {
var inputString=$(this).val();
// use a custom timer to only make the call when the user stops typing
keyupDelay(function(){
if (inputString.length == 0 || inputString == " ") {
$suggestions.fadeOut();
}
else {
$listings.addClass('load');
$.post("autosuggest.php", {
queryString: "" + inputString + ""
}, function(data) {
if (data.length > 0) {
$suggestions.fadeIn();
$('#suggestionsList').html(data);
$listings.removeClass('load');
}
});
}
}, 1000 );
});
$listings.blur(function(){
var thisValue =$(this).val();
// $listings.val(thisValue); // .....this is equivalent to what you had but it doesnt make sense, you're setting its value to itself
$suggestions.delay(1000).fadeOut();
stream = thisValue;
});
// function to handle the keyup timer stuff
var keyupDelay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
});
</script>
.HTML:
<div class="search">
<form id="form" action="search_results.php" method="POST" class="new-search">
<div class="field" id="searchform">
<input type="text" size="25" value="" name="search_term" id="listings" class="" />
<button type="submit" name="submit" value="submit" id="search">Search</button>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="suggestionsList">
</div>
</div>
</div>
</form>
</div>