[英]trouble with comparing strings in javascript
我在JS比較字符串中遇到一個奇怪的問題。 一個字符串來自用戶輸入。
y = data;
document.getElementById("typeThisWord").innerHTML = y;
x = document.getElementById("inputField");
document.getElementById("youTyped").innerHTML = x.value;
first = document.getElementById("youTyped");
second = document.getElementById("typeThisWord");
if(first==second) correct=true;
當單詞相同時,它仍然是錯誤的。 我添加了“第一個”和“第二個”變量,只是看它是否會有所作為。 以前,我嘗試僅將“ x”與“ y”進行比較。 我也嘗試過x.value == y,x == y.value和x.value == y.value。 與“第一”和“第二”相同。 出人意料的是,first.value == second.value一直都是真實的,即使不應該如此。
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var x, y;
var first, second;
var availV = window.innerHeight - 100;
var availH = window.innerWidth - 100;
var randV, randH;
var correct = new Boolean(); correct=true;
var imageX;
function displayWord() {
if(correct) {
correct=false;
$.ajax({
url: "http://localhost:25578/TypeGood/VisitsSession",
success: function(data) { y = data; },
async: false
});
document.getElementById("typeThisWord").innerHTML = y;
imageX = document.createElement("img");
imageX.src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRPRV4XdE7C9sa0pM-FeXcOSQydg7Sh0INg-ZD6FKZ4wjY8WPHa5Q";
imageX.height = 100;
imageX.width = 100;
imageX.style.position = "absolute";
randV = Math.round( Math.random() * availV );
randH = Math.round( Math.random() * availH );
imageX.style.top = randV + "px";
imageX.style.left = randH + "px";
imageX.style.zIndex = "-20";
document.body.appendChild(imageX);
}
x = document.getElementById("inputField");
document.getElementById("youTyped").innerHTML = x.value;
first = document.getElementById("youTyped").innerHTML;
second = document.getElementById("typeThisWord").innerHTML;
if(first==second) {correct=true;}
x.value = "";
}
</script>
getElementById
返回對DOM元素(而不是字符串)的引用,因此您不比較字符串,而是比較DOM元素。 由於它們是不同的元素,因此它們不是==
。
至少,您的最后三行應類似於:
first = document.getElementById("youTyped").innerHTML;
second = document.getElementById("typeThisWord").innerHTML;
if(first==second) correct=true;
(例如,使用元素的innerHTML
,它是一個字符串。)盡管我認為我可能會將值保留在變量中,而不是返回到DOM。
例如:
y = data; //data is string value "First"
將此值更改為新字符串“ first” >>這里f很小
y2 = "first"
現在,當兩者屬於同一類型時,區分大小寫。
if(y==y2)
值是..
First == first
那將是false
。
因此,請確保您在內部html中傳遞數據。 並確保您沒有在其中添加一些空格。
我希望這可以解決問題。 :)
如果修改代碼后仍未解決,請回注:)
使用它代替(first == second):
if(first===second)
並從html檢索值,如下所示:
first = document.getElementById("youTyped").innerHTML;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.