静态 HTML 页面中的 JQuery 搜索,突出显示找到的单词 [英] JQuery search in static HTML page with highlighting of found word
问题描述
我一直在尝试使用 JQuery 在静态 HTML 页面中进行简单的搜索.不得不提的是,这只是我第一次使用 JQuery.
I've been trying to make a simple search inside a static HTML page using JQuery. I have to mention that this is just my first time working with JQuery.
我正在尝试更改页面中找到的单词的背景,这是我迄今为止尝试过的:
I'm trying to change the background of the found word in the page and this is what I've tried so far:
myJavascript.js:
$(document).ready(function(){
$('#searchfor').keyup(function(){
page = $('#all_text').text();
searchedText = $('#searchfor').val();
$("p:contains('"+searchedText+"')").css("color", "white");
});
});
这里还有 HTML 代码:
Here's the HTML code as well:
page.html:
<html>
<head>
<title>Test page</title>
</head>
<body bgcolor="#55c066">
<input type="text" id="searchfor"></input>
<p id="all_text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
<font color="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</font>
</p>
</body>
<script src="jquery-1.7.2.min.js"></script>
<script src="myJavascript.js"></script>
</html>
使用 Firebug 检查页面后,我可以看到 JQuery 中的变量确实从输入字段中获取了值,但我想我搞砸了突出显示部分.
After inspecting the page with Firebug I can see that the variables in JQuery do get the value from the input field but I guess I'm messing up the highlighting part.
预先感谢您的帮助!
推荐答案
做这样的事情
$("p:contains('"+searchedText+"')").each( function( i, element ) {
var content = $(element).text();
content = content.replace( searchedText, '<span class="search-found">' + searchedText + '</span>' );
element.html( content );
});
.search-found {
text-decoration: underline;
}
附言这只有在每个元素"只有纯文本内容时才有效,否则它会删除子节点
p.s. this will work only if each of the "elements" has plain text only content otherwise it would remove children nodes
删除了 each
回调
这篇关于静态 HTML 页面中的 JQuery 搜索,突出显示找到的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!