我不知道如何将以下条件 react 链接到 passid 表单输入 id:
我不知道将 document.querySelector()
方法放在哪里,以便将索引的条件 react 与其相关联。
代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Password - form</title>
</head>
<body>
<form>
<label>Password</label>
<input type="password" id="passid" />
<br>
<input type="submit" value="Sign In" />
</form>
<script>
function passType() {
var password = ["p1", "p2", "p3", "p4", "p5"];
if (password.indexOf > -1) {
alert("That's great! Thank you!");
} else {
alert("Wrong, try again");
}
if (password.indexOf > -1) {
alert("It's wrong, you have one more try...");
} else {
alert("Get out now!");
window.close();
}
}
passType();
</script>
</body>
</html>
应该怎么做?
最佳答案
这些是一些我想关注的点:
- 要使用查询选择器选择特定元素,请记住这些:
- If you happen to know the id of the element, use
document.getElementById(id)
. This is the most prominent way of selection, as usually id is unique for all elements. - If you happen to know the class of the element, use
document.getElementsByClassName(class)
. This method has certain amount of risk, as there could be more than one element with the same class. - If you happen to know the tagName of the element, use
document.getElementsByTagName(tag)
. - The easiest way to achieve element selection is by using
document.querySelector('tag'/ '.class'/ '#id')
. You can refer here for more about the same.
- If you happen to know the id of the element, use
- 现在,您需要了解需要调用您的函数
passType()
,它在这里验证根据您定义的密码数组输入的密码只有在用户输入密码并单击登录按钮后。In order to achieve this, you will have to bind the submit event to an
EventListener
. This can be achieved by usingdocument.querySelector('form').addEventListener('submit', passType);
- 最后,根据您提供的代码片段,您希望给用户第二次机会,以防用户在第一次输入时输入错误的密码。为此,您必须在变量中存储尝试次数。另外,提交操作按钮的
EventListener
一直冒泡,为了防止它,需要使用event.preventDefault()
牢记所有这些,我相信这会解决您的问题。这是修正后的代码片段:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Password - form</title>
</head>
<body>
<form>
<label>Password</label>
<input type="password" id="passid"/>
<br>
<input type="submit" value="Sign In"/>
</form>
<script>
var attemptCount = 0;
function passType(event) {
event.preventDefault();
var enteredValue = document.querySelector('form').querySelector('#passid').value;
var password = ['p1', 'p2', 'p3', 'p4', 'p5'];
if (password.indexOf(enteredValue) > -1) {
alert("That's great! Thank you!");
}
else {
attemptCount++;
alert('Wrong, try again');
if (attemptCount <= 1) {
alert("It's wrong, you have one more try...");
document.querySelector('form').querySelector('#passid').value = '';
} else {
alert('Get out now!');
window.close();
}
}
}
document.querySelector('form').addEventListener('submit', passType);
</script>
</body>
</html>
如有任何疑问,请随时提出。
关于javascript - 如何将条件 react 与 document.querySelector 相关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33245586/