点击

时间:2017-03-02 16:20:49

标签: javascript jquery html css toggle

我有一个<span>,我正在尝试更改点击内容。我已经遵循了一些教程,但我似乎无法做到这一点,所以它会改变。我正在使用unicode字符,所以我认为我需要使用.html()代替.text(),但我可能错了。为什么这不起作用的原因?

以下是我正在使用的来源

$(document).ready(function() {
  $(".dropdownheader").click(function() {
    $("#childList").toggle("slow");
    if ($("#droparrow").html() == '&rtrif;') {
      $("#droparrow").html('&dtrif;');
    } else {
      $("#droparrow").html('&rtrif;');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdownheader">Expected Outcomes of a Corporate Course <span id="droparrow">&dtrif;</span></div>
<div id="childList">
  <ul>
    <li>A better relationship with your coworkers.</li>
    <li>A High Trust and open enivornment.</li>
    <li>A safe and fun environment to work in.</li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:4)

这是因为这个检查:

 if ($("#droparrow").html() == '&rtrif;')

始终评估错误。更好的方法是在元素上存储data-expanded属性,并使用它来确定是否切换 - 记住每次点击都要更新数据项。

$(".dropdownheader").click(function() {
    $("#childList").toggle("slow");
    if($("#droparrow").data("expanded") == "1") {
        $("#droparrow").data("expanded","0").html('&dtrif;');
    } else {
        $("#droparrow").data("expanded","1").html('&rtrif;');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdownheader">Expected Outcomes of a Corporate Course <span id="droparrow" data-expanded="1">&rtrif;</span></div>
    <div id="childList">
        <ul>
            <li>A better relationship with your coworkers.</li>
            <li>A High Trust and open enivornment.</li>
            <li>A safe and fun environment to work in.</li>
        </ul>
    </div>

相关问题