gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:26:31 24 4
gpt4 key购买 nike

考虑这个元素:

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>

知道为什么这行不通吗?当我尝试运行它时,它只输出文本以及我按原样添加的标签,即它显示“”而不是应用它,等等。

最佳答案

您需要 .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>

关于javascript - 使用 jQuery 将不同样式应用于同一元素的各个部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34117255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com