用jquery搜索单词并突出显示
我在jQuery中编写了一个javaScript文件,它提供了一个搜索function。 我试图弄清楚如何突出这个词。 贝娄是代码。
Filter.js:
(function ($) { // custom css expression for a case-insensitive contains() jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) { return function( elem ) { return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; }; }); function listFilter(header, list, title) { // header is any element, list is an unordered list, title is any element // create and add the filter form to the header // create a button for collapse/expand to the title var form = $("
我想要操作的html是由另一个JS文件动态创建的,所以我需要在完全呈现后操纵DOM。我将关注的html呈现为低于,特别是(div中的单词)类= “降价”)。
index.html的:
Description
Response will return details for the connectivity packs based on the ID.
Keywords
foo, bar, helloWorld, java
这是一个使用降价的示例。
- 使用您搜索的单词创建正则表达式。
- 获取
.markdown
的html - 用
"+ word +"
替换该单词。 因此,这会在您搜索的单词周围创建一个span标记。 - 根据需要创建css来设置单词样式。
function highlight(word) { var element = $('.markdown'); var rgxp = new RegExp(word, 'g'); var repl = '' + word + ''; element.html(element.html().replace(word, repl)); } highlight('details');
.marker { background-color: yellow; font-weight: bold; }
Description
Response will return details for the connectivity packs based on the ID.
Keywords
foo, bar, helloWorld, java
看看mark.js。 它可以在特定上下文中突出显示此类搜索词。 在您的示例中,JavaScript看起来像:
var searchTerm = $("#theInput").val(); // Search for the search term in your context $("div.markdown").mark(searchTerm, { "element": "span", "className": "highlight" });
和CSS部分:
span.highlight{ background: yellow; }