Javascript 使用jQuery根据内容加载图标
我有一个网站,内容是从数据库动态加载的。每个标签的内容各不相同 一个可以生成为General:,而另一个可以生成为TV:。 我的问题是,jQuery是否有任何方法可以基于标签的HTML输出将名称:替换为字体图标 例如:Javascript 使用jQuery根据内容加载图标,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个网站,内容是从数据库动态加载的。每个标签的内容各不相同 一个可以生成为General:,而另一个可以生成为TV:。 我的问题是,jQuery是否有任何方法可以基于标签的HTML输出将名称:替换为字体图标 例如: <label>TV:</label> 将成为: <i class="fa fa-film fa-2x"></i> 您可以使用:contains选择器 试一试 变量图标={ "电视:":"电影",, “编辑:”:“编辑” };
<label>TV:</label>
将成为:
<i class="fa fa-film fa-2x"></i>
您可以使用:contains选择器 试一试 变量图标={ "电视:":"电影",, “编辑:”:“编辑” }; $'label'.replaceWithfunction{ var text=$this.text.trim.toLowerCase, 图标=图标[文本]; 返回图标?:未定义; } 电视: TsV: 编辑: 或者,如果您可以在标签中添加类或id,您可以像
$("#ID").html('<i class="YOUR CLASS"></i>');
$(".CLASS").html('<i class="YOUR CLASS"></i>');
例如,您可以用JQuery替换它们
var icons = {
"TV:" : "film"
};
var $labels = $('label');
$labels.each(function(index){
var icon = icons[$(this).text()];
$(this).replaceWith($("<i>").addClass('fa').addClass('fa-' + icon).addClass('fa-2x'));
});
看小提琴:你可以用不同的围裙 我个人最喜欢的是从服务器发送正确的标签 否则,您可以运行以下jQuery脚本: 编辑: 或者像@cforcloud建议的那样
// note: .html does just replace the string "TV:" but leaves the label element in the DOM, while replaceWith is the way to replace an element
// http://api.jquery.com/replacewith/
jQuery("label:contains('TV:')").replaceWith('<i class="fa fa-film fa-2x"></i>');
除了文字外,标签上还有什么其他内容吗?是的,它确实不错,但我想他指的是文本字符串而不是整个标签。@Spokey OP说标签会变成:所以我认为OP非常希望它被替换Hanks,这非常好,正是我想要的!感谢您的帮助,有趣而简洁的解决方案!但如果我有,例如,标签与红色电视,它将取代与足总电影太。但我不需要它。
var icons = {
"TV:" : "film"
};
var $labels = $('label');
$labels.each(function(index){
var icon = icons[$(this).text()];
$(this).replaceWith($("<i>").addClass('fa').addClass('fa-' + icon).addClass('fa-2x'));
});
// try to select as less elements as possible for speed
// for example if they are in a div with class foo try jQuery('div.foo label') instead
var labels = jQuery('label');
// loop throu all labels
labels.each(function() {
// get single label element
var label = jQuery(this);
// get the content (for example "TV:"
var labelContent = label.text();
// replace if the label matches
switch(labelContent) {
case 'TV:':
// if the label contains "TV:" replace the <label> with the <i> element
label.replaceWith('<i class="fa fa-film fa-2x"></i>');
break;
case 'Foo':
// if the label contains "Foo" replace foo with the <i> element
label.html('<i class="fa fa-film fa-2x"></i>');
break;
}
});
// note: .html does just replace the string "TV:" but leaves the label element in the DOM, while replaceWith is the way to replace an element
// http://api.jquery.com/replacewith/
jQuery("label:contains('TV:')").replaceWith('<i class="fa fa-film fa-2x"></i>');