2013-03-08 155 views
-1

我有一個文本字段,用戶可以在其中搜索位置名稱。如何突出顯示結果上的文字,但不包括用戶輸入的內容顯示在結果上?以下是我在jQuery代碼:HTML中的jQuery文本突出顯示

<input maxlength="64" id="war_desc" name="searchtext" size="20" class="form200" autocomplete="off" value=""> 

<div class="auto-complete autocomplete_choices" data-component-bound="true" style="top: 352px; left: 352.5px; width: 172px; display: none;"> 
<ul> 
     <!-- Search result will be append here by html() --> 
</ul> 
</div> 

<script type="text/javascript"> 
$('#war_desc').keyup(function(e){ 
    var search_place = $(this).val(); 
    if(search_place == ''){ 
     $('.autocomplete_choices').hide(); 
    } else { 
     $.ajax({ 
      url:'".$baseUrl."business/searchnew"."', 
      data:{'search_place':$(this).val()}, 
      dataType:'json', 
      Type:'POST', 
      cache:false, 
      success:function(data){ 

       var listHtml = ''; 
       for(var i=0; i<data.length; i++){ 
       listHtml += '<li class="item" data-display-value="Shoe Exchange" title=Shoe Exchange>'+data[i]['business_name']+'</li>'; 
      } 
       $('.autocomplete_choices').show(); 
       $('.autocomplete_choices ul').html(listHtml); 
      } 
     }); 
    } 
}) 
</script> 

以下是描述我的問題的圖像:

enter image description here

謝謝!

+0

的回答,請參閱本http://stackoverflow.com/a/14164015/1920232 – peterm 2013-03-08 03:40:05

+1

OP希望做這個答案的反面 – Popnoodles 2013-03-08 03:42:14

+0

@peterm這是反向夥伴 – d3bug3r 2013-03-08 03:44:23

回答

0

使用的答案在這裏,peterm發現

Simple Text Highlight with jQuery

變化從

$(this).html(text.replace(new RegExp("(" + keywords.join('|') + ")" , 'gi'), "<b>$1</b>")); 

最後一行

$(this).html('<b>' + text.replace(new RegExp("(" + keywords.join('|') + ")" , 'gi'), "</b>$1<b>")) + '</b>'; 

Demo

+0

我如何添加您的代碼與我的? – d3bug3r 2013-03-08 03:51:29

0

您可以使用此簡單的字符串替換方法

var str = "Hello zlippr"; 
str = "Hello"+str.replace(str,"<b>"+str+"</b>").replace("Hello","") 
document.writeln(str) 

您的代碼會是這樣

data[i]['business_name'] = $(this).val()+data[i]['business_name'].replace(data[i]['business_name'],"<b>"+data[i]['business_name']+"</b>").replace($(this).val(),"") 
'<li class="item" data-display-value="Shoe Exchange" title=Shoe Exchange>'+data[i]['business_name']+'</li>'; 
+0

我如何使用它與我上面的代碼?看看listHtml + = – d3bug3r 2013-03-08 04:17:23

+0

我已經更新了代碼,請檢查它 – NARENDRA 2013-03-08 04:20:39