我想通过 jQuery 设置字符串中某个字符的样式,但不知道如何实现。我有以下情况
<a href="" accesskey="i">Link</a>
我自己的方法是:
$('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 小提琴演示 http://jsfiddle.net/davidThomas/M47Rv/.
参考:
-
有属性选择器 http://api.jquery.com/has-attribute-selector/.
-
attr() http://api.jquery.com/attr/.
- replace() https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
- html() http://api.jquery.com/html/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)