繁体   English   中英

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

[英]Apply different styles to parts of the same element using jQuery

考虑这个元素:

德古拉伯爵: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> 

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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM