使用jQuery加载基于<标签>目录

Using jQuery to load icon based on <label> contents

本文关键字:标签 gt 目录 jQuery lt 使用 加载      更新时间:2023-09-26

我有一个网站,其中的内容是从数据库动态加载的。每个标签的内容各不相同。

一个可以生成为General:,而另一个则可以生成为TV:。我的问题是,jQuery有没有办法(基于标签的HTML输出)用一个字体很棒的图标代替NAME:?

例如:

<label>TV:</label>

将变成:

<i class="fa fa-film fa-2x"></i>

尝试

var icons = {
    'tv:': 'film',
    'edit:': 'edit'
};
$('label').replaceWith(function () {
    var text = $(this).text().trim().toLowerCase(),
        icon = icons[text];
    return icon ? '<i class="fa fa-' + icon + ' fa-2x"></i>' : undefined;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css">
<label>TV:</label>
<label>TsV:</label>
<label>EDIT:</label>

您可以使用:contains选择器http://api.jquery.com/contains-selector/

$("label:contains('TV')").html('<i class="fa fa-film fa-2x"></i>');
$("label:contains('TV')").html('<i class="YOUR CLASS"></i>');

或者,如果你可以在标签中添加class或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'));
});

参见Fiddle:http://jsfiddle.net/m19hjnoa/

您可以对此采取不同的解决方案。

我个人最喜欢的是从服务器发送正确的标签。

否则,您可以运行此jQuery脚本:http://jsfiddle.net/ehdgL6so/

// 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;
    } 
});

编辑:或者正如@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>');