我想使用jQuery在段落中查找一段文本并添加CSS使其加粗。但我似乎无法弄清楚为什么下面的代码不起作用:
$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').css({'font-weight':'bold'});
});
“about_theresidency”中的文本是动态获取的,因此在窗口加载后我执行它。
replace()
和html()
方法:var html = $('p').html();
$('p').html(html.replace(/world/gi, '<strong>$&</strong>'));
编辑: http://jsbin.com/AvUcElo/1/edit
我把它变成了一个小插件,这里:
$.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']
});
words: ['"world"', '"red"']
- elclanrs我曾经遇到类似的问题,尝试使用elclanrs提出的解决方案。它很好用,但前提是您要修改的文本中没有任何HTML元素。如果文本中包含任何标签,则在运行wrapInTag
函数后这些标签将会丢失。
下面是我的内部节点友好型解决方案(我还包含了编写代码所使用的资源链接)。
// https://dev59.com/zWkw5IYBdhLWcg3wlbd3#9795091
$.fn.wrapInTag = function (opts) {
// https://dev59.com/kXI-5IYBdhLWcg3w18V3#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 + '>';
// https://dev59.com/xnVC5IYBdhLWcg3wbgdS#298758
$(this).contents().each(function () {
if (this.nodeType === 3) //Node.TEXT_NODE
{
// https://dev59.com/WlzUa4cB1Zd3GeqPzArq#7698745
$(this).replaceWith(getText(this).replace(regex, replacement));
}
else if (!opts.ignoreChildNodes) {
$(this).wrapInTag(opts);
}
});
};
this.nodeType == Node.TEXT_NODE
而不是检查 this.nodeType === 3
。 - Jason Axelson在IE7中无法工作,但是
this.nodeType === 3`在大多数浏览器中都可以工作。 - jahuregex = RegExp('(^|\\s)' + words.join('(\\s|$)|(^|\\s)') + '(\\s|$)', 'gi'),
这将仅匹配由空格限定的完整单词。在我的情况下,我正在构建一个拼写检查器,因此我只需要高亮显示完整单词。 - Sean尝试:
$(window).load(function() {
// ADD BOLD ELEMENTS
$('#about_theresidency:contains("cross genre")').each(function(){
$(this).html(
$(this).html().replace(/cross genre/g,'<strong>$&</strong>')
);
});
});
我已经采用并调整了@jahu提供的代码,使其可以添加数据属性,然后在DOM上运行回调函数,以便在您的模板中存在像这样的代码:$('foo').wrapInTag(...)
<p data-js-highlight-text="hello,">
<span style="color: #009fff">Hello,</span> World
</p>
// Extended examples with data attributes in your html:
//
// Set the data-js-highlight-text attribute. Before:
<p data-js-highlight-text="hello,">Hello, World</p>
// After:
<p data-js-highlight-text="hello,"><span style="color: #009fff">Hello,</span> World</p>
需要一种更安全的方法,可以进行转义。这里有一个基本解决方案。
var str = 'The world is big <b onclick="alert(false)">world</b> red. the world is also small'
var words = ['world', 'is']
var reg = RegExp(words.join('|'), 'gi')
var p = document.createElement('p')
p.innerText = str
p.innerHTML = p.innerHTML.replace(reg, '<u>$&</u>')
document.body.appendChild(p)
console.log(p.outerHTML)
<div class="content"> <h1>关于我们</h1> <span id="about_theresidency"></span>
- Michael$('#about_theresidency:contains("cross genre")').wrap("<b></b>");
但是没有成功。 - Michael