简体   繁体   English

从HTML获取数据并将其存储到$(window).load()

[英]Get data from HTML and store into $(window).load()

HTML: HTML:

<form>
   <input type="text" id = "userText"/>
   <button onclick="getData()">Send</button>
</form>

Javascript: 使用Javascript:

  var inputUser;
  // I tried this and it didn't work either

  function getData(){
    inputUser = document.getElementById("userText").value;
    alert(inputUser);
  }

  $(window).load(
    function(){ * something * })

I can get data in function getData() but can't access that data into $(window).load(function()). 我可以在函数getData()中获取数据,但是不能将该数据访问到$(window).load(function())中。

If I put document.getElementById() or try to use inputUser in * something * code. 如果我放置document.getElementById()或尝试在*某些*代码中使用inputUser It's return nothing. 它什么也没返回。 I want use the text input from user in * something *. 我想在*东西*中使用来自用户的文本输入。

So how can i do this? 那我该怎么办呢? Thanks! 谢谢!

The load event fires at the moment when the user has loaded the document. 当用户加载文档时,将触发加载事件。

At that point, the user hasn't typed anything into the form. 此时,用户尚未在表单中输入任何内容。

You can't get the text input in that function because it doesn't exist yet . 您无法在该函数中获取文本输入,因为它尚不存在

You declared var inputUser inside getData() , therefore you can only access it inside getData() (it's called a scope). 您在getData()声明了var inputUser ,因此只能在getData()访问它(称为作用域)。

Declare it outside (just above) with var inputUser; var inputUser;在外面(上面)声明它var inputUser; . Then, inside getData() just set it with inputUser = ... (without another var ) and then you can access it from $(window).load . 然后,在getData()内部,只需使用inputUser = ...设置它(不带另一个var ),然后可以从$(window).load访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM