简体   繁体   English

getElementById没有在Javascript中选择元素

[英]getElementById not selecting element in Javascript

I am trying to create an event based on the DOM for testing my Javascript skills, anyone knows why this isn't applying to the element? 我正在尝试创建一个基于DOM的事件来测试我的Javascript技能,任何人都知道为什么这不适用于该元素?

function getButton(){
    var getButton = document.getElementById("submit");
    getButton.onclick() = function(){
         alert("it works!")
    }
}

Submit is an <input type="submit" /> type of element from the element by Id, so I don't get it why it wouldn't work. 提交是一个<input type="submit" />元素的元素来自元素,所以我不明白为什么它不起作用。

Drop the () in the event identifier. 删除事件标识符中的() You are just assigning a property here and do not make a function call or similar. 您只需在此处分配属性,而不进行函数调用或类似操作。

function getButton(){

  var getButton = document.getElementById("submit");

  getButton.onclick = function(){
     alert("it works!");
  }
}
getButton.onclick = function() {
       alert("it works!");
};

You have several problems in your code: 您的代码中有几个问题:

  1. The element you're trying to submit is a <submit> tag; 您尝试提交的元素是<submit>标记; it doesn't have id="submit" , so trying to get the element getElementById("submit") isn't going to work. 它没有id="submit" ,所以试图获取元素getElementById("submit")是行不通的。

    Either give your <submit> tag its own id and select by that, or use getElementByTagName("submit") instead. 要么将<submit>标记赋予其自己的idgetElementByTagName("submit")选择,要么使用getElementByTagName("submit")代替。

  2. As the @Sirko and @Osiris have mentioned, getButton.onclick() = function(){ isn't working because you're trying to call .onclick() as a function when it's not. 正如@Sirko和@Osiris所提到的, getButton.onclick() = function(){无效,因为你试图将.onclick()作为函数调用。 What you want to do is to assign a function to the onclick attribute of getButton : 你想要做的是为getButtononclick属性分配一个函数:

    getButton.onclick() = function(){ should be getButton.onclick = function(){ . getButton.onclick() = function(){应该是getButton.onclick = function(){

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

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