jQuery - onPage search like a browser
I try to make onpage searches like in modern browsers with STRG + F. I tried:
$("#mydiv").find(':contains(\'mySearchString\'开发者_Python百科)').prepend('found you!');
The problem is that jQuery adds found you multiple times, bedause there are multipile elements who has the string. Example:
Found you<div>
Found you<ul>
Found you<li>
Found you<a>mySearchString</a>
</li>
</ul>
</div>
$('#mydiv').find(':contains(\'mySearchString\')').contents().filter(function(){return this.nodeType == Node.TEXT_NODE}).prepend('found you!');
would only select the last inner text node. If you are using IE, use the constant 3 instead of Node.TEXT_NODE.
You could do:
$("#mydiv").find(':contains(\'mySearchString\')').eq(0).prepend('found you!');
to single out the first match.
Otherwise you could just say it works like Google Chrome, which highlights all search matches immediately ;)
精彩评论