jQuery即时搜索点击文本进行选择

时间:2015-12-03 17:37:28

标签: jquery

我是jQuery的新手,我试图进行即时搜索。 当我选择包含键的div("结果" div)时,一切正常,但我需要在div中选择键时使其工作(带有&#34的跨度文本; name" id)。 谢谢!

以下是代码:

$(function(){
$(".search").keyup(function() 
{ 
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
    $.ajax({
    type: "POST",
    url: "searchbrand.php",
    data: dataString,
    cache: false,
    success: function(html)
    {
    $("#result").html(html);
    }
    });
}return false;    
});



jQuery("#result").on("click",function(e){ 
    var $clicked = $(e.target);
    var $name = $clicked.find(\'.name\').html();
    var decoded = $("<div/>").html($name).text();
    $(\'#searchid\').val(decoded);
});


jQuery(document).on("click", function(e) { 
    var $clicked = $(e.target);
    if (! $clicked.hasClass("search")){
    jQuery("#result").fadeOut(); 
    }
});
$(\'#searchid\').click(function(){
    jQuery("#result").fadeIn();
});
});

</script>



<div class="content2">
<input type="text" class="search" id="searchid" placeholder="Search brand"/>
<div id="result"></div>
</div>';

和searchbrand.php ...

 $q = mysql_real_escape_string($_POST['search']);
    $result = mysql_query("select DISTINCT brand FROM general WHERE brand LIKE '%$q%' ORDER BY id LIMIT 10");

$nr=mysql_numrows($result);
$i=0;
while( $i<$nr)
     {
      $brand=mysql_result($result,$i,"brand");
          $i++;  
          $b_brand = '<strong>'.$q.'</strong>';        
          $final_brand = str_ireplace($q, $b_brand, $brand);  

echo'       <div class="show" align="left" >
                <img src="/images/arrow.png" style="height:15px; float:left; margin-right:2px;" /><span class="name">'.$final_brand.'</span>
            </div>';

    }

0 个答案:

没有答案