简体   繁体   English

如何将变量从 HTML 文件传递到 JavaScript 文件

[英]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.

相关问题 如何将变量从 html 文件传递​​到 javascript 文件 - how to pass a variable from html file to javascript file 如何将Javascript变量传递到HTML文件 - How to pass a Javascript variable into a HTML file 将Flask HTML Template中的变量传递给JavaScript文件以供使用 - Pass variable from Flask HTML Template to JavaScript file for use 如何将 Object 值从 Javascript 文件传递到 HTML 文件 - How to Pass Object Value From A Javascript File to HTML File 将 HTML 文件内容传递给 JavaScript 变量 - Pass HTML File content to JavaScript variable 如何将变量从HTML脚本文件传递到Google Apps脚本中的javascript函数? - How can I pass a variable from an HTML script file to a javascript function in google apps script? 如何将元素值变量从 Javascript html 文件传递到 google apps 脚本中的 code.gs 文件? - How to pass an element-value variable from Javascript html file to code.gs file in google apps script? 如何将变量从html表单传递到.js文件? - How to pass a variable from a html form to a .js file? 如何将变量从 javascript 函数传递到 php 文件而不重新加载编写 javascript 函数的当前 html 页面? - how to pass a variable from javascript function to php file without reloading the current html page in which javascript function is written? 如何将数组变量从javascript传递到pug文件? - How to pass an array variable from javascript to a pug file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM