2017-03-02 33 views
2

變化內容我有一個<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

有沒有'類= 「droparrow」'元素在你的HTML。它是'id =「droparrow」',所以選擇器應該是'#droparrow'。 – Barmar

+0

@Barmar呃,我以爲我解決了這個問題。現在已經修復了。現在它會改變一次,但它不會改變點擊。 –

+1

問題是'.html()'不返回實體代碼,它返回它轉換爲的Unicode字符。嘗試'console.log($(「#droparrow」)。html())'看看。 – Barmar

回答

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>

+0

這樣做。謝謝你的幫助!當StackOverflow讓我哈哈時,我會接受答案 –