如何为javascript switch语句的文本输出添加背景色



我有一个正在运行的代码字符串,正确的输出显示在网站上。如果情况3是正确的;接受";打印时,我必须在文本中添加一个绿色背景,上面写着";接受";。我该怎么做?感谢

getLatestMessage(thread: Thread): string {
const message = thread.messages.slice().reverse()[0];
if (message && message.type === 0) {
return message.content;
} else {
return '';
}
}
getLatestSystemMessage(thread: Thread): string {
const message = thread.messages.slice().reverse().find(m => m.type !== 0);
const isUserOwner = thread.project.user.id === this.user.id;
let content = '';
if (message) {
switch (message.type) {
case 1:
if (<any>message.content > 0) {
content = isUserOwner ?
`Offered you $${message.content}` :
`You offered $${message.content}`;
} else {
content = isUserOwner ?
`Offered to translate for free` :
`You offered to translate for free`;
}
break;
case 2:
content = isUserOwner ?
'Cancelled offer' :
'You cancelled your offer';
break;
case 3:
content = isUserOwner ?
'You accepted the offer' :
'Accepted';
break;
case 4:
content = isUserOwner ?
"You accepted another translator's offer" :
"Accepted another translator's offer";
break;
}
}

这是模板

<p class="mb-0"><strong>{{getLatestSystemMessage(thread)}}</strong></p>

如果只需要根据文本值应用背景颜色,即";批准";,您可以将html内容中的模板变量用作

<p class="mb-0">
<strong #t1 [ngClass]="{'bg-green': t1.innerText === 'Approved'}">{{getLatestSystemMessage(thread)}}</strong>
</p>

定义bg类绿色

.bg-green {
background: green;
}

替代解决方案(不太推荐(是将此模板引用作为第二个参数传递给getLatestSystemMessage函数,在切换的情况3中,使用

t1.classList.add('bg-green');

注意:

只需使用CSS。根据模板系统的不同,您只需要根据变量值设置它。

const statusBg === "Accepted" ? "style="background: green"":"";
<p class="mb-0" {{statusBg}}><strong>{{getLatestSystemMessage(thread)}}</strong></p>

最新更新