【问题标题】:Applying CSS to words/letters in html document using jQuery or PHP [duplicate]使用 jQuery 或 PHP 将 CSS 应用于 html 文档中的单词/字母 [重复]
【发布时间】:2012-11-26 16:54:26
【问题描述】:

可能重复:
Find text string in jQuery and make it bold

假设我有一个这样的html文档

<div>
hi this is one line<br>
<p>This is second line</p>
<p>This 'word' is within quote</p>
<p>Another 'lorem ipsum' in quote</p>
</div>

我如何将不同的 CSS 仅应用于在我的文档中多次出现的单词“line”,以及使用 jQuery 将不同的 CSS 应用于出现在引号内的所有单词。某种模式匹配和应用 css

有任何可用的脚本吗?

【问题讨论】:

    标签: javascript jquery html css jquery-plugins


    【解决方案1】:

    你可以像这样使用 JQuery contains 选择器:

    http://jsfiddle.net/z4ZwF/

    function replaceText(textToSearch,classToApply)
    {
      $('div').html($('div').html().replace(new RegExp(textToSearch, 'g'),"<span class='"+classToApply+"'>"+textToSearch+"</span>"));
    }
    

    例如:replaceText("'lorem ipsum'",'red')replaceText("line",'red')

    编辑

    在搜索和替换中添加引号换行:http://jsfiddle.net/z4ZwF/3/

    function replaceText(textToSearch,classToApply,searchAndWrapQuote)
    {
        searchAndWrapQuote = searchAndWrapQuote || false;
        quote = (searchAndWrapQuote) ? "'" : "";
    
      $('div').html($('div').html().replace(new RegExp(quote+textToSearch+quote, 'g'),"<span class='"+classToApply+"'>"+quote+textToSearch+quote+"</span>"));
    }
    
    replaceText("lorem ipsum",'red',true)
    

    【讨论】:

    • 添加小提琴jsfiddle.net/z4ZwF
    • 但是如果我必须将 css 应用于所有单词,包括引号内的引号,该怎么办?
    • 用引号将文本括起来,例如 replaceText("'lorem ipsum'",'red') jsfiddle.net/z4ZwF/2
    • 我的意思是默认情况下用引号括起来的任何单词..我们对引号之间的值进行硬编码..
    • 顺便说一句,我喜欢你的代码..它简短而简单:)
    【解决方案2】:

    您不能将任何样式直接应用于“行”字。您需要的是解析内容并将您的“行”包装到某个标签 - 例如,之后您可以将 CSS 中的一些样式应用于此类。 您可以在 php 和 javascript 中执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2021-11-12
      • 1970-01-01
      • 2015-08-22
      • 2014-11-21
      相关资源
      最近更新 更多