在Ajax建议框中使用Jquery更改类

时间:2012-10-03 17:24:36

标签: jquery ajax search autosuggest

我正在创建一个建议搜索框,当我按下或按下以查看建议时,它会短暂更改为新的高亮类,然后恢复为默认值。问题似乎是当我用这行searchReq.open("GET", '/search/ajax-suggest.php?search=' + str, true);调用我的php时。如果我将out和硬代码值注释到我的search_suggest div中,那么该功能正常。这个php页面只是用一个新的行字符回显出来的值。

我在html页面上的输入是

<form id="frmSearch" action="/search/index.php" method="get">

            <input type="text" id="zoom_query" name="zoom_query" alt="Search Criteria" onkeyup="searchSuggest(); " autocomplete="off"  />
            <input type="image" src="/images/search_button.gif" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" /><br/>
            <div id="search_suggest">
            </div>
                        </form> 

在我的js页面上我有

function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
} else if(window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
} else {
    alert("Your Browser is out of date");
}
}

//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();

//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() { 
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
    var str = escape(document.getElementById('zoom_query').value);
    searchReq.open("GET", '/search/ajax-suggest.php?search=' + str, true);
    searchReq.onreadystatechange = handleSearchSuggest; 
    searchReq.send(null);   
}       
}

//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
    var ss = document.getElementById('search_suggest')
    ss.innerHTML = '';
    var str = searchReq.responseText.split("\n");
    for(i=0; i < str.length - 1; i++) {
    var suggest = '<div class="suggest_link">' + str[i] + '</div>';
        ss.innerHTML += suggest;
    }
}
}
$(document).keyup(function(e) {
var $hlight = $('div.suggest_link_over'), $div = $('div.suggest_link');
if (e.keyCode == 40) {
    $hlight.removeClass('suggest_link_over').next().addClass('suggest_link_over');
    if ($hlight.next().length == 0) {
        $div.eq(0).addClass('suggest_link_over')
    }
} else if (e.keyCode === 38) {
    $hlight.removeClass('suggest_link_over').prev().addClass('suggest_link_over');
    if ($hlight.prev().length == 0) {
        $div.eq(-1).addClass('suggest_link_over')
    }
}
})

0 个答案:

没有答案