我试图瞄准下一个'。'在使用jquery的标题中。
所以现在标题是
<h1 class="page-head">Explore. Think. Connect.</h1>
我的jquery是
$(h1.page-head:contains(.)').each(function(){
$(this).html(
$(this).html().replace('.','<span class=\'nice-point\'>.</span>')
);
});
我想知道如何定位其他2'。'单独为它们添加样式。
任何帮助将不胜感激!
答案 0 :(得分:2)
使用the overload of .html()
which accepts a function:
$('h1.page-head:contains(.)').html(function (index, oldHtml) {
return oldHtml.replace(/\./g, '<span class="nice-point">.</span>');
});
如果您想为.
中的每个oldHtml
执行不同的操作,您可以获得更高级的since replace()
accepts a function as well,或者您可以使用任何其他所需的字符串操作:
$('h1.page-head:contains(.)').html(function (index, oldHtml) {
// equivalent to the code above; just an example
return oldHtml.split('.').join('<span class="nice-point">.</span>');
});
答案 1 :(得分:0)
如果要对出现的每个匹配项应用特定样式,可以按照文本中出现的点的顺序排列要应用的样式。
等。
$("h1.page-head:contains(.)").each(function(){
newHTML = $(this).html()
.replace('.','<span style=\'color:#F00;\'>.</span>')
.replace('.','<span style=\'color:#40F;\'>.</span>')
.replace('.','<span style=\'color:#0F4;\'>.</span>')
$(this).html(newHTML);
});
这是一个demo fiddle
以上示例分别将style=\'color:#F00;\'
应用于第一个点,style=\'color:#40F;\'
到第二个点,style=\'color:#0F4;\'
到第三个点。我认为这就是你为每个点单独添加样式的意思。对不起,如果我错了。