2016-12-09 4 views
0

HTMLでHTMLエンティティとボタンに取り組んでいないJavascriptの比較は名前

<button id="the_button" onclick="clicked()">&darr; Source &darr;</button> 

Javascriptを

上記のコードでは
function clicked() { 
    if ($("#the_button").html() == "&darr; Source &darr;") { 
     alert($("#the_button").html()); 
    } 
} 

は、私が...警告ポップアップを得ることはありません

ただし、ボタンのテキストと比較文字列を変更して、HTMLエンティティなしでSourceにすると、動作します。

HTML

<button id="the_button" onclick="clicked()">Source</button> 

Javascriptを

function clicked() { 
    if ($("#the_button").html() == "Source") { 
     alert($("#the_button").html()); 
    } 
} 

は、HTMLエンティティ&darr;と連携持つ方法はありますか?

+1

あなたは ' "\ u2193ソースの\ u2193"'と比較した場合、それは動作しますか? – Pointy

+2

いずれにせよ、それを識別するために '

+1

これは少し最適ではないデザインですが、HTMLエンティティを扱いたくない場合は、矢印と「ソース」というテキストを3つのスパンで囲み、「ソース」を含む中間のHTMLのみをチェックしてください。私はハンドラとして 'clicked()'関数を使って複数のボタンがあると仮定していますか? – Shilly

答えて

3

私はJSは実体ではなく、参照を見ていると信じています。下矢印(\u2193)のユニコード文字参照を使用してみてください。

var $btn = $('#the_button'); 
 

 
$btn.on('click', function() { 
 

 
    var html = $btn.html(); // or .text() 
 
    
 
    if ('\u2193 Source \u2193' === html) { 
 
    \t alert(html); 
 
    } 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="the_button">&darr; Source &darr;</button>

参考資料:Unicode Table(UnicodeとHTML参照を提供します)。

2

これは動作するはずです:

function clicked() { 
    if ($("#the_button").html() == '\u2193 Source \u2193') { 
     alert($("#the_button").html()); 
    } 
} 
1

あなたはエンティティ名のASCIIコードを知っているリンクhttp://www.ascii-code.com/html-symbol.phpを参照してください

function clicked() { 
    if ($("#the_button").text() === $('<span>&darr; Source &darr;</span>').text()) { 
     // .... 
    } 
} 
1

aswell偽の要素を使用することができます。 エスケープシーケンスの使用方法については、https://mathiasbynens.be/notes/javascript-escapesのリンクを参照してください。

function clicked() { 
 
    if (document.getElementById("the_button").innerHTML == " \u2193 Source \u2193") { 
 
     alert(document.getElementById("the_button").innerHTML); 
 
    } 
 
}
<button id="the_button" onclick="clicked()"> &darr; Source &darr;</button>