首页 > 解决方案 > 如何让 onClick() 从我的 javascript 文件中读取?

问题描述

我有两个文件index.htmlindex.js. 当我填写表单中的文本字段并单击按钮时,它应该重定向到index.js. 我该如何做到这一点?

索引.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1 id="head">Hello</h1>
    <input type="email" id="email"></input>
    <br><br>
    <input type="password" id="pass"></input>
    <br><br>
    <button>Click</button>
    
    <script src="index.js"></script>
    
</body>
</html>

index.js

if (document.getElementById("email").nodeValue==document.getElementById("pass").nodeValue){
        alert("You are allowed");
}

编辑:我可以简单地通过在<script>标签本身内创建函数然后onClick<button>标签内调用函数来做到这一点。但是相反,我想onClick调用我的index.js脚本来执行后端的东西

标签: javascripthtml

解决方案


在 index.js 中声明这个函数

function handleClick() {
  if (
    document.getElementById('email').nodeValue ===
    document.getElementById('pass').nodeValue
  ) {
    alert('You are allowed');
  }
}

点击按钮调用它

<button onclick="handleClick()">Click</button>

推荐阅读