4

ページをレンダリングするときに dom 属性 (ツールチップ) に配置されるツールチップを処理するカスタム JS スクリプトがいくつかあります。

ただし、このツールチップ (div として表示) を取得しようとすると、javaScript は属性値を自動的にエスケープ解除するようです。これは正常な動作ですか?これを回避する方法はありますか?

私が抱えている問題は、 <email@example.org> が (無効な) html に変わることです。

再現例:

<div tltip ="&lt;text&gt;" id="escaped" />
<div tltip ="<text>"id="notescaped" />

js:

a  = document.getElementById("escaped").getAttribute("tooltip");
b  = document.getElementById("notescaped").getAttribute("tooltip");
a.match("<"); //returns true (unexpected)
a.match("<"); //returns true (expected)
a == b; // returns true (unexpected)

編集:

明確にするために、(div)ツールチップを表示しようとしており、次のようなコンテンツを何らかの形で読み取りたい場合は 、dom から「 <email@example.org>"<b> &lt;email@example.com&gt <\b>" のように見えるはずの div に表示します。

4

1 に答える 1

6

It's not JavaScript which "unescapes" the characters, but the HTML parser which decodes the entities. It's expected behaviour.

If it does not sound logical to you, tell me how you would put a double and a single quote in an attribute.

<div tltip=""'">          does not work.
<div tltip="&quot;'">     does work.
<div tltip='"&#39;'>      does work.
<div tltip="&quot;&#39;"> does work.

Regarding the edited question
You don't have to read the original source code. For instance:

<div tltip="&lt;b&gt;test&lt;/b&gt;" id="test"></div>

var output1 = document.getElementById('html');
var output2 = document.getElementById('plain');
var attrValue = document.getElementById('test').getAttribute('tltip');
output1.innerHTML = attrValue;
output2.textContent = attrValue;

Will render as:

Output 1: test
Output 2: <b>test</b>

textContent is not supported in old IE versions. A cross-browser compatible way is:

output2[document.textContent === null ? 'textContent' : 'innerText'] = attrValue;
// OR
output2.innerHTML = ''; // Empty contents
output2.appendChild(document.createTextNode(attrValue));

If you still want to decode the entities, then the following will work:

// <b> -> &lt;b&gt;
function decode(strHTML) {
    var tmp = document.createElement('div');
    tmp.appendChild(document.createTextNode(strHTML));
    return tmp.innerHTML;
}
于 2012-06-27T10:43:03.840 に答える