Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

javascript - How to compare an html entity with jQuery

I have the following html code:

<h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3>

I would like to toggle between up arrow and down arrow each time the user clicks the span tag.

function expandCollapse(id) {   
    var arrow = $("#"+id+" span").html(); // I have tried with .text() too
    if(arrow == "&dArr;") {     
        $("#"+id+" span").html("&uArr;");               
    } else {        
        $("#"+id+" span").html("&dArr;");               
    }
}

My function is going always the else path. If I make a javacript:alert of arrow variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the arrow variable as a string and not as html.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When the HTML is parsed, what JQuery sees in the DOM is a UPWARDS DOUBLE ARROW ("?"), not the entity reference. Thus, in your Javascript code you should test for "?" or "u21d1". Also, you need to change what you're switching to:

function expandCollapse(id) {
    var arrow = $("#"+id+" span").html();
    if(arrow == "u21d1") {     
        $("#"+id+" span").html("u21d3");                           
    } else {            
        $("#"+id+" span").html("u21d1");                           
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...