我在JS比较字符串时出现了一个奇怪的问题。一个字符串来自用户输入。在javascript中比较字符串的麻烦
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>
谢谢。它也在做同样的事情 - 它认为这两个因素在平等的时候是不相等的。我正在把我的JS块放在上面。 – user2155320 2013-03-12 02:03:39
@ user2155320:两个不同*元素*永远不会相等。这就是我的答案。 – 2013-03-12 07:36:43