[英]How to pass variable from an HTML file to a JavaScript file
I have two different files: a.html and a.js.我有两个不同的文件:a.html 和 a.js。 In the html file I have a button, that when I click it I call a function located inside the.js file.
在 html 文件中,我有一个按钮,当我单击它时,我会调用位于 .js 文件中的 function。 In this moment, when I click the button, I want to pass a parameter that I receive from an on the html file to the js one.
此时,当我单击按钮时,我想将从 html 文件中收到的参数传递给 js 文件。 I've tried, from the js, to do Document.getElementById("idDelInput") but since the input is not inside the same file, it doesn't recognise the Document.
我已经尝试从 js 中执行 Document.getElementById("idDelInput") 但由于输入不在同一个文件中,因此它无法识别 Document.getElementById("idDelInput")。
function login() { //check the variable email }
<input id="email" type="text"> <button onClick="login()">Login</button>
You need to grab the element first into your Javascript and then get the value from it.您需要先将元素抓取到 Javascript 中,然后从中获取值。
document.getElementById("email")
, or document.querySelector("#email")
will get your element into the javascript file. document.getElementById("email")
或document.querySelector("#email")
会将您的元素放入 javascript 文件中。 Then use value
property to get its value.然后使用
value
属性来获取它的值。
function login() { document.querySelector("#email").value; }
<input id="email" type="text"> <button onClick="login()">Login</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.