由于某种原因,我的JavaScript函数无法工作。我想在h1标签上使用onclick。在下面的片段中,它工作得很好。但当我在Chrome上试用它时,它什么也做不了。任何帮助都是非常感谢的。
function loginDetails() {
alert("Username: somebody\nPassword: pass123");
}
<!DOCTYPE html>
<html>
<head>
<title>Login Screen</title>
<link rel="javascript" type="text/javascript" href="login.js">
</head>
<body>
<div id="container">
<h1 onclick="loginDetails()">Login</h1>
<form>
<label for="username" class="label-1">Username</label><br>
<input type="text" id="username" class="text-box"><br>
<label for="password" class="label-2">Password</label><br>
<input type="text" id="password" class="text-box"><br>
<button type="submit" id="login" class="button">Sign In</button>
</form>
</div>
</body>
</html>
发布于 2020-06-14 21:10:31
外部JS是用<script src="..."></script>
而不是<link>
元素添加的。
如果您已经通过验证器运行了您的代码,它将突出显示您的错误。
发布于 2020-06-14 21:07:30
嘿,试试这个密码,
<html>
<head>
<title>Login Screen</title>
<link rel="javascript" type="text/javascript" href="login.js">
</head>
<body>
<div id="container">
<h1 onclick="loginDetails()">Login</h1>
<form>
<label for="username" class="label-1">Username</label><br>
<input type="text" id="username" class="text-box"><br>
<label for="password" class="label-2">Password</label><br>
<input type="text" id="password" class="text-box"><br>
<button type="submit" id="login" class="button">Sign In</button>
</form>
</div>
<script>
function loginDetails(){
alert('You Clicked on H1!')
}
</script>
</body>
产出:
发布于 2020-06-14 21:12:21
实际上,您的代码可以工作(当前的代码片段)。
更好的方法是删除"onclick“属性并创建事件侦听器。
const h1 = document.querySelector('h1');
h1.addEventListener('click', loginDetails);
https://stackoverflow.com/questions/62378069
复制相似问题