开发者

How to target specific letter/word with jquery?

As a mere example, I want to apply the class "fancy" to all occurrences of the sign "&" in the document.

The CSS:

.fancy { font-style: italic; }

So a text that looks like this:

Ben & Jerry's

would be manipulated开发者_如何学编程 by jquery to this:

Ben <span class="fancy">&amp;</span> Jerry's

Is there a function to target specific words/phrases/letters like this?


This isn't something that jQuery is generally helpful with--it works more at the node level than the text/html level. However, this might help (source):

$('p:contains(&)').each(function(){
  $(this).html(
    $(this).html().replace('&amp;','<span class=\'fancy\'>&amp;</span>')
  );
});

Obviously if you can restrict the initial search to something better than all paragraphs, it'd perform better. You should also test it to see if the :contains filter actually helps.

It's not pretty but it seems to work.


There's a "highlight" plugin that does almost exactly what you describe:

http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html


Regex is commonly used for this:

http://chirale.wordpress.com/2009/07/04/character-substitution-on-jquery/

http://forum.jquery.com/topic/how-to-select-specific-characters-and-replace-them

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜