我在算div孩子。这是带有id结果的div,它是接受ajax结果的容器。问题是,当我在搜索框中输入内容(即实时搜索)时,我的计数器会显示搜索框之前值的结果。例如,当我输入“bel”时,它显示我对“be”的计数,依此类推。为什么会这样,以及如何让它像容器div中的任何变化一样工作“live”计数器?
$('#search, #description').on("keyup", function(){
if($('#search_results').length>0){
$('#search_results').remove();
}
$('#browse_wrapper').prepend("<p style='border-bottom: 1px solid #C5C5C5; margin-bottom: 20px;' id='search_results'><span class='glyphicon glyphicon-info-sign'></span> <strong>"+$('div#results>div').length+"</strong> results for "+$('#search, #description').val()+"</p>");
});
Ajax代码:
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var city = $('input#search').val();
var description = $('input#description').val();
//$('b#search-string').html(query_value);
if(city !== '' || description !== ''){
$.ajax({
type: "POST",
url: "ajax_php/search.php",
data: { city: city, desc: description},
cache: false,
success: function(html){
$("div#results").html(html);
}
});
}return false;
}
$("input#search, input#description").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string_1 = $(this[0]).val();
var search_string_2 = $(this[1]).val();
// Do Search
if (search_string_1 == '' || search_string_2 == '') {
$("div#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("div#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
答案 0 :(得分:1)
不是将代码放在keyup
函数中,而是在字段填充数据后立即在success
函数中设置计数器,您可以对其进行计数。
代码:
// Live Search
// On Search Submit and Get Results
function search() {
var city = $('input#search').val();
var description = $('input#description').val();
//$('b#search-string').html(query_value);
if (city !== '' || description !== '') {
$.ajax({
type: "POST",
url: "ajax_php/search.php",
data: {
city: city,
desc: description
},
cache: false,
success: function (html) {
$("div#results").html(html);
$('#search_results').remove();
$('#browse_wrapper').prepend("<p style='border-bottom: 1px solid #C5C5C5; margin-bottom: 20px;' id='search_results'><span class='glyphicon glyphicon-info-sign'></span> <strong>" + $('div#results>div').length + "</strong> results for " + $('#search, #description').val() + "</p>");
}
});
}
return false;
}
答案 1 :(得分:0)
您的网页搜索结果是动态的,因此您需要使用event delegation method:
$(document).on("keyup",'#search, #description', function(){
答案 2 :(得分:0)
您可以尝试使用setTimeout()
与clearTimeout()
:
var t = "";
$('#search, #description').on("keyup", function(){
clearTimeout(t);
t = setTimeout(function(){
if($('#search_results').length>0){
$('#search_results').remove();
}
$('#browse_wrapper').prepend("<p style='border-bottom: 1px solid #C5C5C5; margin-bottom: 20px;' id='search_results'><span class='glyphicon glyphicon-info-sign'></span> <strong>"+$('div#results>div').length+"</strong> results for "+$('#search, #description').val()+"</p>");
},500);
});