首页 > 解决方案 > 如何遍历列表以及何时包含单词更改颜色

问题描述

所以我需要用一个按钮创建一个搜索字段,当你在搜索字段中输入一个单词然后按下该按钮时,它需要遍历一个列表。并且当列表中包含您输入的单词时,项目(单词)的背景颜色需要更改。

我用 HTML 中的按钮和列表创建了一个搜索字段。我用 JQuery 写了一些东西,但我真的需要帮助。这很难。

$(document).ready( function() {

    $("button").click(function(){
        $("li").each(function(i, element){
            if($(this).css {
                return = '#304878';
            }
        });
    })

});

标签: jquery

解决方案


单击搜索按钮时,在字符串中用颜色突出显示搜索文本。 在此处输入图像描述 试试下面的代码。

$(document).ready( function() {
	$("button").click(function(){
		
		//Remove the span tag from the text which have class 'highlight'
		$('.add_content').find("span").each(function(index) {
			if($(this).hasClass('highlight')){
				var text = $(this).text();
				$(this).replaceWith(text);
			}
		});
		
		//On click get the search text and highlight. 
		var string_search =  $('#search_box').val();
		$('li').each(function(){
		
			//Enable the case insensitive
			reg = new RegExp(string_search, 'gi');
			$(this).html($(this).html().replace(reg, function(str) {
				return '<span class="highlight">'+str+'</span>'
			}));
		});
	});
});
.highlight{
	color:#304878;
}
   

 <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <input type="text" id="search_box" name = "search_box">
    <button name="search_buttoon">Search Button</button>
   <ul class="add_content">
	<li>Lorem Ipsum is simply dummy</li>
	<li>ndustry. Lorem Ipsum has been</li>
	<li>It is a long established fact that a reader</li>
</ul>
        

   


推荐阅读