在jQuery中替换HTML实体

时间:2015-10-01 22:14:57

标签: jquery html

我有以下html,这是一个dl标签,其中包含一个带有切换类并包含常见问题解答的dt标签,然后是一个带有扩展类的dd标签,其中包含常见问题解答的答案:

<dl>
<dt class="toggle">&#9660; Here is a FAQ</dt>
<dd class="expand">
    <p>And here is the answer</p>
</dd>
....
</dl>

以及以下jQuery:

$(function () {
    $('.expand').hide();

    $('.toggle').click(function() {
        var $expand = $(this).next('.expand');
        if ($expand.is(':hidden')) {
            $expand.slideDown();
        } else {
            $expand.slideUp();
        }
    });
});

此功能可扩展或折叠FAQ答案。

我真正想要做的是在文本展开时用▲向上箭头替换▼向下箭头。我不想使用图像或精灵。

无论我如何编码/使用切片或子串函数,到目前为止我都无法实现这一点。

任何评论都表示赞赏,但要善意,因为这是我的第一篇文章。

3 个答案:

答案 0 :(得分:1)

将箭头放在<i>标记内,以便您可以使用jQuery定位它:

<dt class="toggle"><i>&#9660;</i> Here is a FAQ 1</dt>

示例

$(function () {

  $('.expand').hide();

  $('.toggle').click(function() {
    var $expand = $(this).next('.expand');
    var isHidden = $expand.is(':hidden');
    $expand.slideToggle();
    $("i", this).html(isHidden? "&#9650;" : "&#9660;");
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
  <dt class="toggle"><i>&#9660;</i> Here is a FAQ 1</dt>
  <dd class="expand">
    <p>1 And here is the answer</p>
  </dd>
  <dt class="toggle"><i>&#9660;</i> Here is a FAQ 2</dt>
  <dd class="expand">
    <p>2 And here is the answer</p>
  </dd>
  <dt class="toggle"><i>&#9660;</i> Here is a FAQ 3</dt>
  <dd class="expand">
    <p>3 And here is the answer</p>
  </dd>
</dl>

答案 1 :(得分:1)

另一个选择就是依靠CSS显示隐藏上下箭头。

$(".toggle").on("click", function () {
    $(this).toggleClass("open");
});
.toggle {
    cursor: pointer;  
}

.toggle > span + span {
  display : none;
}

.toggle.open > span {
  display : none;
}

.toggle.open > span + span {
  display : inline;
}

.toggle + dd.expand { display : none; } 
.toggle.open + dd.expand { display : block;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
<dt class="toggle"><span>&#9650</span><span>&#9660;</span> Here is a FAQ</dt>
<dd class="expand">
    <p>And here is the answer</p>
</dd>
</dl>

答案 2 :(得分:0)

您可以使用字符的Unicode值替换HTML实体。

字符▼为十进制9660,十六进制为25BC。因此,它的HTML实体为&#9660;,其JavaScript字符串形式为"\u25BC"

同样适用于▲,十进制为9650,十六进制为25B2

因此,您可以使用以下方法在文本字符串中来回替换:

.replace("\u25BC", "\u25B2");

工作示例:

$(function () {
    $('.expand').hide();

    $('.toggle').click(function() {
        var $this = $(this);
        var $expand = $this.next('.expand');
        if ($expand.is(':hidden')) {
            $expand.slideDown();
            $this.text($this.text().replace("\u25BC", "\u25B2"));
        } else {
            $expand.slideUp();
            $this.text($this.text().replace("\u25B2", "\u25BC"));
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl>
<dt class="toggle">&#9660; Here is a FAQ</dt>
<dd class="expand">
    <p>And here is the answer</p>
</dd>
....
</dl>