我想要做的是使用jQuery在段落中查找一段文本并添加一些CSS以使其变为粗体.我似乎无法弄清楚为什么这不起作用:
$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});
Run Code Online (Sandbox Code Playgroud)
"about_theresidency"中的文本被动态拉入,因此我在窗口加载后执行它.
elc*_*nrs 82
你可以用replace()与html():
var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
Run Code Online (Sandbox Code Playgroud)
编辑: http ://jsbin.com/AvUcElo/1/edit
我把它变成了一个lil'插件,在这里:
$.fn.wrapInTag = function(opts) {
var tag = opts.tag || 'strong'
, words = opts.words || []
, regex = RegExp(words.join('|'), 'gi') // case insensitive
, replacement = '<'+ tag +'>$&</'+ tag +'>';
return this.html(function() {
return $(this).text().replace(regex, replacement);
});
};
// Usage
$('p').wrapInTag({
tag: 'em',
words: ['world', 'red']
});
Run Code Online (Sandbox Code Playgroud)
jah*_*ahu 14
我有类似的问题,并尝试使用elclanrs提出的解决方案.它工作得很好,但前提是你想要改变的文本中没有html元素.如果文本中有任何标记,则在运行该wrapInTag函数后它们将丢失.
这是我对内部节点友好的解决方案(我包含了用于编写代码的资源的链接).
// http://stackoverflow.com/a/9795091
$.fn.wrapInTag = function (opts) {
// http://stackoverflow.com/a/1646618
function getText(obj) {
return obj.textContent ? obj.textContent : obj.innerText;
}
var tag = opts.tag || 'strong',
words = opts.words || [],
regex = RegExp(words.join('|'), 'gi'),
replacement = '<' + tag + '>$&</' + tag + '>';
// http://stackoverflow.com/a/298758
$(this).contents().each(function () {
if (this.nodeType === 3) //Node.TEXT_NODE
{
// http://stackoverflow.com/a/7698745
$(this).replaceWith(getText(this).replace(regex, replacement));
}
else if (!opts.ignoreChildNodes) {
$(this).wrapInTag(opts);
}
});
};
Run Code Online (Sandbox Code Playgroud)
示例:http://jsbin.com/hawog/1/edit