我使用此iambriansreed中的topic代码来加粗一些文字,并且其工作正常。但是我希望在同一页面上的所有标题ID中找到像BMW,Mini Cooper等多个单词并且它不起作用。这是示例http://zazl.linuxpl.info/title/ 有任何想法吗?我根本不是jquery程序员。
这是代码:
$(window).load(function() {
// ADD BOLD ELEMENTS
$('#titleh:contains("Mini Cooper")').each(function(){
$(this).html(
$(this).html().replace(/Mini Cooper/g,'<span class="firstWord">$&</span>')
);
});
$('#titleh:contains("BMW")').each(function(){
$(this).html(
$(this).html().replace(/BMW/g,'<span class="firstWord">$&</span>')
);
});
});
答案 0 :(得分:0)
它不起作用的原因是因为您的文档中有多个具有相同ID的元素。因此,当您按ID选择元素时,它只选择具有该ID的第一个元素。
在HTML文档中,ID 必须唯一。使用类代替:
<span class="titleh">...</span>
对于您的JavaScript:
$(window).on('load', function() {
$('.titleh').each(function() {
var $e = $(this),
html = $e.html();
html = html.replace(/Mini Cooper/g, '<span class="firstWord">$&</span>');
html = html.replace(/BMW/g, '<span class="firstWord">$&</span>');
/* Add more rules here */
$e.html(html);
});
});