我有一个包含名称的项目列表。 然后我有一个eventlistener,它为keypress事件ckecks。 如果用户键入i.g. a A以A开头的所有名称都应以A粗体显示。所以所有的首发应该是大胆的。
使用jquery只能突出显示字符串的一部分的最佳方法是什么?
感谢您的帮助
答案 0 :(得分:0)
有jQuery插件可以进行文本突出显示,但是我没有看到突出部分文字的插件。
一种可能的解决方案是将所有名称放在页面上,第一个字母用<span>
标记包围,并带有一个类:
<span class='A FL'>A</span>ugustine
<span class='C FL'>C</span>arlos
然后你可以使用jQuery按类名来捣乱。
$('whatever').keypress(function(ev) {
var k = e.which.toUpperCase();
$('#textContainer span.FL').css('font-weight', 'normal');
$('#textContainer span.' + k).css('font-weight', 'bold');
});
请注意,粗体字符比普通字符更胖,因此这会产生用户可能不喜欢的“摇摆”效果。您可以考虑改变颜色。
答案 1 :(得分:0)
这是您在按键事件期间可以调用的功能,以突出显示搜索字符串:
function Highlight(search)
{
$('ul > li').each(function() {
if (this.innerHTML.indexOf(search) > -1)
{
var text = $(this).text();
text = text.replace(search, "<span id='highlight' style='font-weight: bold'>" + search + "</span>");
$(this).html(text);
}
else
{
this.innerHTML = $(this).text();
}
});
}
测试html:
<ul id='list'>
<li>Bob Jones</li>
<li>Red Smith</li>
<li>Chris Edwards</li>
</ul>
它不像Pointy的答案那么优雅,但它处理匹配的字符串要求。
答案 2 :(得分:0)
感谢您的帮助...... 我想通了,详细的解决方案来了:
var communities = $('#mylist').find('.name');
var temp_exp = new RegExp("^("+match_string+")","i");
communities.each(function(i){
var current = $(this);
var name = current.text();
name = name.replace(temp_exp, '<b>$1</b>');
current.html(name);
});
虽然所有项目都必须有“名称”类。