1

I want to highlight the first 10 characters of text and also color occurrences of the word "paragraph".

<html>
 <body>
  This is a heading
  This is a paragraph.This is another paragraph.
 </body>
</html>
4

2 回答 2

4

将其视为您的 HTML 内容:

<div id="contents">
    This is a heading
    This is a paragraph.This is another paragraph.
</div>

此 jQuery 代码将执行您想要的操作:

$(document).ready(function() {
    var data = $('#contents').text().trim();

    var str = "";

    for(var i = 0; i < 10; i++) {
        str += data[i];
    }

    data = data.replace( /paragraph/g, '<span style="font-weight: bold;">paragraph</span>' );
    data = data.replace( str, '<span style="background-color: yellow;">' + str + '</span>' );

    $('#contents').html( data );
});
于 2012-07-22T06:21:14.863 回答
1

在 JS 中尝试此代码。

<!DOCTYPE html>
    <html>
    <body>

    <p>Click the button to highlight.</p>

    <p id="demo">This is a heading. This is a paragraph. This is another paragraph.</p>

    <button onclick="myFunction()">Try it</button>

    <script type="text/javascript">
    function myFunction()
    {
        var str= document.getElementById("demo").innerHTML;
        var str1 = "";

        for(var i = 0; i < 10; i++) {
            str1 += str[i];
        }
    var n=str.replace(str1,'<span style="font-weight: bold;">' + str1 + '</span>');
    document.getElementById("demo").innerHTML=n;
    }
    </script>

    </body>
    </html>
于 2012-08-10T06:26:47.640 回答