使用jQuery将不同的样式应用于同一元素的各个部分

Apply different styles to parts of the same element using jQuery

本文关键字:元素 个部 样式 jQuery 使用 应用于      更新时间:2023-09-26

考虑这个元素:

德古拉伯爵:布莱布莱布莱

我需要以这样一种方式分割文本,即冒号之前(包括冒号)的部分有一种样式(比如粗体和红色),其余部分有另一种风格(比如黑色和斜体)。

我正在尝试使用JQuery来实现这一点,下面是我的尝试:

$("vi").each(function(){
   var temp = $(this).text();
   temp = temp.split(':');
   temp[0] = "<strong>" + temp[0].trim() + "</strong>";
   temp[1] = "<em>" + temp[1].trim() + "</em>";
   temp = temp.join("");
   $(this).text(temp);
});
vi {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<html>
<body>
<vi>Dracula: bleh bleh bleh</vi>
</body>
</html>

知道为什么这不起作用吗?当我尝试运行它时,它只是按原样输出文本和我添加的标签,即它显示"而不是应用它,依此类推

您需要.html(),而不是.text(),因为您要将HTML插入元素:

$("vi").each(function(){
   var temp = $(this).text();
   temp = temp.split(':');
   temp[0] = "<strong>" + temp[0].trim() + "</strong>";
   temp[1] = "<em>" + temp[1].trim() + "</em>";
   temp = temp.join("");
   $(this).html(temp);
});

此外,如果我理解你想要的描述,你的CSS样式应该是:

vi strong {
  color: red;
}

注意:vi不是一个有效的HTML元素,但您可能已经知道了。

$("vi").each(function(){
   var temp = $(this).text();
   temp = temp.split(':');
   temp[0] = "<strong>" + temp[0].trim() + "</strong>";
   temp[1] = "<em>" + temp[1].trim() + "</em>";
   temp = temp.join(": ");
   $(this).html(temp);
});
vi strong {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<vi>Dracula: bleh bleh bleh</vi>

html()设置为元素。阅读http://api.jquery.com/html

$("vi").each(function(){
   var temp = $(this).text();
   temp = temp.split(':');
   temp[0] = "<strong>" + temp[0].trim() + "</strong>";
   temp[1] = "<em>" + temp[1].trim() + "</em>";
   temp = temp.join(": ");
   $(this).html(temp);
});
vi {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<html>
<body>
<vi>Dracula: bleh bleh bleh</vi>
</body>
</html>

您需要使用$.fn.html方法。将其与函数参数一起使用很方便,它将在内部为您运行each循环:

$("vi").html(function(_, text) {
    text = text.split(':');
    return "<strong>" + text[0].trim() + "</strong> <em>" + text[1].trim() + "</em>";
});
vi {color: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<vi>Dracula: bleh bleh bleh</vi>