为字符串中的某个字符设置样式
我想通过jQuery在字符串中设置某个字符的样式,但不知道如何处理它。 我有以下情况
Link
现在我想在可点击链接中为accesskey
(所以在这种情况下为‘i’ )中的字符加下划线。 所以’Link’中的’i’应该加下划线
有人知道吗?
我自己的方法是:
$('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,'' + aKey + ''); // 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小提琴演示 。
参考文献:
- has-attribute选择器 。
-
attr()
。 -
replace()
-
html()
我用动态范围替换了“i”:
var jq = $('a'); var text = jq.text().replace(jq.attr('accessKey'), 'i'); jq.html(text);
如果只是针对这种情况,我会在HTML中而不是在JQuery中执行:
Link
注意:删除链接的默认下划线需要“text-decoration:none”,尽管您应该在CSS中设置它。
这是这种方法的小提琴。
如果您仍想使用JQuery,可以将链接样式和内部html更改为上面的内容。
有一个名为“突出显示”的插件,它会根据搜索字符串突出显示一些文本。 插件在这里 。
有关使用说明, 请参阅此文章 。 (我前段时间为Smashing写过)