使用jQuery对同一元素的不同部分应用不同的样式

4
考虑这个元素:

Count Dracula: Bleh bleh bleh

我需要将文本分割成两个部分,冒号之前(包括冒号)的部分有一种样式(如加粗红色),其余部分有另一种样式(如黑色斜体)。
我正在尝试使用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>

有什么原因导致这段代码不能正常运行吗?当我尝试运行它时,它只是将文本和我添加的标签一起输出,即它显示了 "" 而不是应用它。

请使用<span>标签包裹相应的部分。不要让它太难。 - Mikel
3个回答

1
你需要使用.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>


1
将元素的 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>


1
你需要使用$.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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接