jQuery替换 - 造型数字

时间:2015-08-12 05:03:59

标签: javascript jquery css

我想在我的< code>中设置特定字符的样式标签。 所以我google并找到了.replace()函数。但我在造型上有问题。我想改变它的风格而不改变它的文字。

这是我的代码:

HTML

<code> $years = floor($diff / (365*60*60*24)); </code>

JS

('code').each(function()
{
    var text = $(this).text(); 
    var setan = text.replace(/\d+/g,'<int>'+'\d'+'</int>');
    $(this).html(setan); 
});

输出为$years = floor($diff / (d*d*d*d));

我想至少像$years = floor($diff / (<b>d</b>*<b>d</b>*<b>d</b>*<b>d<b>));

那样

3 个答案:

答案 0 :(得分:4)

最好使用css类来设置元素的样式,如

$('code').html(function() {
  var text = $(this).text();
  return text.replace(/\d+/g, '<span class="d">' + 'd' + '</span>');
});
code span.d {
  font-weight: bold;
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<code> $years = floor($diff / (365*60*60*24)); </code>

答案 1 :(得分:2)

  

我想至少像$years = floor($diff / (<b>d</b>*<b>d</b>*<b>d</b>*<b>d</b>));

那样

尝试使用<b></b>替换<int></int>代替.html(function(index, html){})替换文字

$("code").html(function(_, html) {
    return html.replace(/\d+/g,"<b>d</b>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<code> $years = floor($diff / (365*60*60*24)); </code>

答案 2 :(得分:2)

据我所知,你想要在那里展示数字,而不是d字母。

您可以使用捕获组进行替换 这就是你如何做到这一点:

$("code").each(function() {
    var text = $(this).text();
    $(this).html(text.replace(/(\d+)/g, '<int>$1</int>')); // here you can place any tags
});
int { 
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<code>$years = floor($diff / (365*60*60*24));</code>