说我有这个HTML元素:
<td>—</td>
当浏览器解析时,—
会转换为实际的em-dash,如下所示:
<td>—</td>
如何在不使用JavaScript代码中的其他字符的情况下测试—
?
console.log(elem.innerHTML == "—"); // false
console.log(elem.textContent == "—"); // false
console.log(elem.innerHTML == "—"); // true
console.log(elem.textContent == "—"); // true
答案 0 :(得分:3)
emdash的unicode等价物是\u2014
。您可以使用此unicode与html进行比较。
HTML meta的默认编码设置为UTF
,因此所有实体都转换为UTF-8。阅读更多https://developer.mozilla.org/en/docs/Web/HTML/Element/meta#Attributes
var dash = document.getElementById('dash').innerText;
alert(dash === '\u2014');
&#13;
<div id="dash">—</div>
&#13;
答案 1 :(得分:3)
您可以创建一个新的DOM元素,然后比较两者:
/**
* Test that a DOM element's inner HTML is === —
*/
function mdashTest(el) {
var tempEl = document.createElement('div');
tempEl.innerHTML = '—';
return el.innerHTML === tempEl.innerHTML;
}
// Test it!
elem = document.getElementById('dash');
alert( mdashTest( elem ) );
<div id="dash">—</div>
答案 2 :(得分:2)
我建议:
DOMParser()
function parseToText(code) {
return new DOMParser().parseFromString('<em>' + code + '</em>', "text/html").firstChild.textContent;
}
var is = document.getElementById('text').innerHTML == parseToText("—");
document.write("isEquals ", is, parseToText("—"));
<em id="text">—</em>
function parseToText(code) {
return $("<em>" + code + "</em>").html()
}
var isEquals = document.getElementById('text').innerText == parseToText("—");
document.write("isEquals ", isEquals);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<em id="text">—</em>
function parseToText(code) {
return document.createRange().createContextualFragment(code).firstChild.textContent;
}
var isEquals = document.getElementById('text').innerText == parseToText("—");
document.write("isEquals ", isEquals);
<em id="text">—</em>