gpt4 book ai didi

javascript - 在javascript中比较字符串的麻烦

转载 作者:行者123 更新时间:2023-11-30 18:07:59 25 4
gpt4 key购买 nike

我在 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。

关于javascript - 在javascript中比较字符串的麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15332417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com