设置字符串中某个字符的样式 [英] Style a certain character in a string

查看:99
本文介绍了设置字符串中某个字符的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过jQuery为字符串中的某个字符设置样式,但不知道如何实现.我有以下情况

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

<a href="" accesskey="i">Link</a>

现在,我想在可点击链接中的accesskey(在这种情况下为'i')中加下划线.因此,链接"中的"i"应加下划线

Now i want to underline the character in the accesskey (so the 'i' in this case) in the clickable link. So the 'i' in 'Link' should be underlined

有人知道吗?

推荐答案

我自己的方法是:

$('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演示.

参考文献:

  • has-attribute selector.
  • attr().
  • replace()
  • html()

这篇关于设置字符串中某个字符的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆