仅当使用jQuery在搜索框中显示文本时显示消息

Displaying message only when text in search box with jQuery

本文关键字:显示 文本 消息 搜索 jQuery      更新时间:2023-09-26

我有一个用jQuery编写的Google Instant风格的搜索脚本,它可以查询PHP文件。目前,当没有找到结果时,PHP文件不会返回HTML代码,因此脚本会显示一条消息,说"没有找到结果"。但是,当搜索框中没有搜索词,并且查询字符串为空时,仍会显示此消息。如何获取它,以便只有在搜索框中有文本时才显示消息?

这是我的jQuery代码:

$(document).ready(function(){
    $("#search").keyup(function(){
        var search=$(this).val();
        var query=encodeURIComponent(search);
        var yt_url='search.php?q='+query+'&category=web';
        window.location.hash='search/'+query+'/1/';
        document.title=$(this).val()+" - My Search Script";
        if(search==''){
            window.location.hash='';
            document.title='My Search Script';
        }
        $.ajax({
            type:"GET",
            url:yt_url,
            dataType:"html",
            success:function(response){
                if(response !=""){
                $("#result").html(response);
                } else {
                $("#result").html("No results were found.");
                }
            }
        });
    });
});

即使搜索字段中没有任何内容,请求仍在激发。只有在字段不为空时才发出请求。