以下代码片段演示了我的问题。当我测试包含“&”的字符串时,结果始终为 false。
这应该如何处理?请仅使用 JavaScript 解决方案。
var PROJECT = "This & Somthing Else";
var PROJECT2 = "This and Somthing Else";
function testValues()
{
if (PROJECT == document.getElementById("curPrjct").innerHTML)
{
alert("The Same");
}else{
alert("Not The Same");
}
}
function testValues2()
{
if (PROJECT2 == document.getElementById("curPrjct2").innerHTML)
{
alert("The Same");
}else{
alert("Not The Same");
}
}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<span id="curPrjct">This & Somthing Else</span> <br>
<input type="button" value="Go This will fail" onclick="testValues()"><br><br>
<span id="curPrjct2">This and Somthing Else</span> <br>
<input type="button" value="Go This will work" onclick="testValues2()">
</body>
</html>
最佳答案
尝试查看 HTML 的问题是,当它转换为 DOM 然后再转换回 HTML 时,它将被标准化。
&
将转换为 &
。
比较 textContent
而不是 HTML。
var PROJECT = "This & Somthing Else";
var PROJECT2 = "This and Somthing Else";
function testValues()
{
if (PROJECT == document.getElementById("curPrjct").textContent)
{
alert("The Same");
}else{
alert("Not The Same");
}
}
function testValues2()
{
if (PROJECT2 == document.getElementById("curPrjct2").textContent)
{
alert("The Same");
}else{
alert("Not The Same");
}
}
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<span id="curPrjct">This & Somthing Else</span> <br>
<input type="button" value="Now this will work" onclick="testValues()"><br><br>
<span id="curPrjct2">This and Somthing Else</span> <br>
<input type="button" value="Go This will work" onclick="testValues2()">
</body>
</html>
关于javascript - 在 JavaScript 中测试两个值的相等性,其中内容包含 &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328905/