fontawesome 的 append() 或 appendTo()

append() or appendTo() for fontawesome

我有这个场景。

在标题中<h2></h2>我想在文本前放置字体图标。 前任。

  <h2 id="test"><i class="fa fa-cog"></i> THIS IS TITLE</h2>

我会为所有标题添加手动图标,但如果任何标题留空(没有图标),脚本会添加默认图标

  <i class="fa fa-angle-double-left"></i>

我试过这个脚本,但它不起作用。

$("#test(:empty)").append('<h2><i class="fa fa-angle-double-left"></i></h2>');

有什么解决这个问题的建议吗?

编辑 我需要这个用于侧边栏中的所有块。块的结构是:

        <div class="sidebar">
        <h2><i class="fa fa-users"></i><a href="#"> Title 1</a></h2>
        <ul>
                        <li>

                            <div class="user"></div>
                        </li>
        </ul>
    </div>

和 2-nt 侧边栏相同 class 不同的标题

        <div class="sidebar">
        <h2><i class="fa fa-users"></i><a href="#"> Title 2</a></h2>
        <ul>
                        <li>

                            <div class="user"></div>
                        </li>
        </ul>
    </div>

第 3 块没有图标

        <div class="sidebar">
        <h2>HERE ADDD DEFAULT ICON <a href="#"> Title 1</a></h2>
        <ul>
                        <li>

                            <div class="user"></div>
                        </li>
        </ul>
    </div>    

我希望现在已经清楚了

您正在将 h2 附加到 h2。更好的是,将 html 设置为:

$("#test(:empty)").html('<i class="fa fa-angle-double-left"></i>');

另外,你不应该给多个元素相同的 id。为此,您应该使用 class 并像这样调用:

$(".test(:empty)").html('<i class="fa fa-angle-double-left"></i> My default title!');

in title <h2></h2> i want to put fontawesome icon before text

$("h2(:empty)").html(function(){
    return "<i class="fa fa-angle-double-left"></i>"+this.innerText;
});

注意 $('#test(:empty)') 将搜索带有 #test 的第一个元素,我猜你已经有一个 h2 非空。

should not 具有相同 ID 的元素,它在文档中必须是唯一的。使用 data-* 属性 - data-id

<h2 data-id="test">....

$("h2[data-id='test'](:empty)")

或class

<h2 class="test">....

$("h2.test(:empty)")

您可以通过 CSS 使用 Pseudo-Classes 来完成。

.sidebar h2:empty:before {font-family: 'FontAwesome';content: '\f100';}
.sidebar h2:before {font-family: 'FontAwesome';content: '\f0c0';}

<div class="sidebar">
    <h2>User Name</h2>
</div>

JSFiddle