Style a certain character in a string

前端 未结 4 1302
名媛妹妹
名媛妹妹 2021-01-26 00:37

I want to style a certain character in a string via jQuery, but have no clue how to approach that. I have the following situation



        
相关标签:
4条回答
  • 2021-01-26 01:05

    I replaced the "i" with a span dynamically:

    var jq = $('a');
    var text = jq.text().replace(jq.attr('accessKey'), '<span style="text-decoration: underline;">i</span>');
    jq.html(text);
    

    http://jsfiddle.net/FishBasketGordo/QGEzA/

    0 讨论(0)
  • 2021-01-26 01:07

    My own approach would be:

    $('a[accesskey]').each( //selects only those a elements with an accesskey attribute
        function(){
            var aKey = $(this).attr('accesskey'); // finds the accesskey value of the current a
            var text = $(this).text(); // finds the text of the current a
            var newHTML = text.replace(aKey,'<span class="access">' + aKey + '</span>');
            // creates the new html having wrapped the accesskey character with a span
            $(this).html(newHTML); // sets the new html of the current link with the above newHTML variable
        });
    

    JS Fiddle demo.

    References:

    • has-attribute selector.
    • attr().
    • replace()
    • html()
    0 讨论(0)
  • 2021-01-26 01:13

    There's a plugin called "Highlight" which will highlight bits of text based on a search string. Plugin here.

    For usage instructions, see this article. (I wrote for Smashing a while ago)

    0 讨论(0)
  • 2021-01-26 01:17

    If it is just for this case, I would do it in the HTML rather than in JQuery:

    <a href="" accesskey="i" style="text-decoration:none">L<u>i</u>nk</a>
    

    Note: The "text-decoration:none" is needed to remove the default underline for links, though you should probably set this in CSS.

    Here's a fiddle for that method.

    If you still want to do it with JQuery, you can just change the link style and inner html to the above.

    0 讨论(0)
提交回复
热议问题