我正在尝试比较 javascript 中的两个变量
Im trying to compare two variable in javascript
它会定义一个变量,如果您键入的内容相同,则它会定义另一个变量,如果您键入的内容相同,则它具有变量,它表示正确的单词,如果它们不相同,则表示错误的单词。我的问题是总是说错词
function wordcompare() {
var word1 = "word";
var typed = document.getElementById("word");
if (typed === word1) {
alert("Correct word");
} else {
alert("Incorrect word");
}
}
您必须将输入值与 word
进行比较。你要比较的是字符串 word
和 HTMLElement
由 document.getElementById( "word" )
返回
当您使用 getElementById
查询任何元素时,它会返回与您作为 argument
传入的 id
相匹配的 HTMLElement
function wordcompare() {
var word1 = "word";
var typed = document.getElementById("word").value;
if (typed === word1) {
alert("Correct word");
} else {
alert("Incorrect word");
}
}
document.querySelector("button").addEventListener("click", wordcompare);
<input type="text" id="word">
<button> compare </button>
因此,我假设您有一个输入元素和一个按钮,当您单击按钮时,它会调用函数进行比较。
您需要从输入元素中获取值,否则您只是返回元素,无法与之进行比较。
// Cache the elements
const input = document.querySelector('input');
const button = document.querySelector('button');
// When the button is clicked call the function
button.addEventListener('click', wordCompare, false);
function wordCompare() {
const word1 = 'word';
// Get the value from the input element and
// then make the comparison
if (input.value === word1) {
console.log('Correct word');
} else {
console.log('Incorrect word');
}
}
<input />
<button>Check word</button>
它会定义一个变量,如果您键入的内容相同,则它会定义另一个变量,如果您键入的内容相同,则它具有变量,它表示正确的单词,如果它们不相同,则表示错误的单词。我的问题是总是说错词
function wordcompare() {
var word1 = "word";
var typed = document.getElementById("word");
if (typed === word1) {
alert("Correct word");
} else {
alert("Incorrect word");
}
}
您必须将输入值与 word
进行比较。你要比较的是字符串 word
和 HTMLElement
由 document.getElementById( "word" )
当您使用 getElementById
查询任何元素时,它会返回与您作为 argument
id
相匹配的 HTMLElement
function wordcompare() {
var word1 = "word";
var typed = document.getElementById("word").value;
if (typed === word1) {
alert("Correct word");
} else {
alert("Incorrect word");
}
}
document.querySelector("button").addEventListener("click", wordcompare);
<input type="text" id="word">
<button> compare </button>
因此,我假设您有一个输入元素和一个按钮,当您单击按钮时,它会调用函数进行比较。
您需要从输入元素中获取值,否则您只是返回元素,无法与之进行比较。
// Cache the elements
const input = document.querySelector('input');
const button = document.querySelector('button');
// When the button is clicked call the function
button.addEventListener('click', wordCompare, false);
function wordCompare() {
const word1 = 'word';
// Get the value from the input element and
// then make the comparison
if (input.value === word1) {
console.log('Correct word');
} else {
console.log('Incorrect word');
}
}
<input />
<button>Check word</button>