简体   繁体   English

JavaScript不允许在运行前输入

[英]JavaScript not allowing input before running

Im having issues with this javascript running prior to the user input, can someone help me fix this. 我在用户输入之前运行此javascript时遇到问题,有人可以帮助我解决此问题。

im just trying to make a little html page with a textbox and a button, that then clicked opens a new windows with a modified URL. 我只是试图让一个小的HTML页面的文本框和一个按钮,然后是点击打开与修改后的URL一个新的窗口。

<input type="text" name="enter" class="enter" value="" id="lolz" />
<button type="button" id="the_button">Count</button>

document.getElementById('open').addEventListener('click', myFunction());
function myFunction() {
  var button = document.getElementById("the_button");
  var siteid = document.getElementById('lolz').value
  button.onclick = count();

  function count() {
    window.location = "http://www.websiteimusing.com/" + siteid;
  }
 }

You can check the code out here The Actually generate output from that website's code is this 您可以在此处查看代码。实际从该网站的代码生成输出是这样的

Updated Code 更新的代码

document.getElementById('the_button').addEventListener('click', myFunction);
 function myFunction() {
   var button = document.getElementById("the_button");
   var siteid = document.getElementById('lolz').value
    button.onclick = count();

 function count() {
     window.location = "http://www.websiteimusing.com/" + siteid;
   }
  }

Change to: 改成:

document.getElementById('open').addEventListener('click', myFunction);

When you put () after a function name, it means to call the function at that time. 当在函数名称后加上()时,表示此时调用该函数。

There's no element with id open in your code, so you're trying to add an event listener to null. 您的代码中没有open ID为id的元素,因此您尝试将事件侦听器添加为null。 The console will tell you the same: 控制台将告诉您相同的内容:

Uncaught TypeError: Cannot call method 'addEventListener' of null

Also make sure to remove the parens from your event listener function, as the other posters have stated. 还要确保从事件侦听器功能中删除括号,如其他张贴者所述。

On this line 在这条线上

document.getElementById('open').addEventListener('click', myFunction());

you are calling the function by adding the () 您通过添加()来调用函数

change that to: 更改为:

document.getElementById('open').addEventListener('click', myFunction);

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

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