是否可以将此查询缩短为一个?
$('p:contains(Tel:)').html(function() {
return $(this).html().replace('Tel:', '<strong>Tel:</strong>');
});
$('p:contains(Fax:)').html(function() {
return $(this).html().replace('Fax:', '<strong>Fax:</strong>');
});
我的代码查找电话:和传真:并使用<strong>
标记
答案 0 :(得分:5)
您可以将它们合并为:
$('p:contains(Tel:), p:contains(Fax:)').html(function(_, html) {
return html.replace(/(Tel\:|Fax\:)/g, '<strong>$1</strong>');
});
但实际上这有点多余:你要求jQuery在你自己做之前进行第一次搜索。
我个人更喜欢这个:
$('p').each(function() {
var html = $(this).html();
var changed = html.replace(/(Tel\:|Fax\:)/g, '<strong>$1</strong>');
if (changed!=html) $(this).html(changed);
});
Demonstration(点击“使用JS运行”)