最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addEventListener not working on html button - Stack Overflow

programmeradmin0浏览0评论

Simple html button that I want to alert when clicked.

HTML:
<div id="container>
    <button type="button>Click Me</button>
</div>

Javascript:
var cat = document.getElementById("container");
var dog = cat.getElementsByTagName("button");
function mouse (){
    alert("mouse")
};
dog.addEventListener("click", mouse, false);

If I target the container with:

cat.addEventListener("click", mouse, false);

Works fine anytime I click on the div, but when I try to add it to the button, nothing happens. I have also tried...

dog.addEventListener("click, mouse(), false);

When I try that code, the mouse function runs on load.

Simple html button that I want to alert when clicked.

HTML:
<div id="container>
    <button type="button>Click Me</button>
</div>

Javascript:
var cat = document.getElementById("container");
var dog = cat.getElementsByTagName("button");
function mouse (){
    alert("mouse")
};
dog.addEventListener("click", mouse, false);

If I target the container with:

cat.addEventListener("click", mouse, false);

Works fine anytime I click on the div, but when I try to add it to the button, nothing happens. I have also tried...

dog.addEventListener("click, mouse(), false);

When I try that code, the mouse function runs on load.

Share Improve this question edited Jul 29, 2014 at 16:21 Brian asked Jul 29, 2014 at 16:14 BrianBrian 3153 gold badges7 silver badges12 bronze badges 1
  • 2 getElementsByTagName returns an array of node list. There are actually multiple errors there with missing quotes in HTML, button close tag having a typo etc. – Harry Commented Jul 29, 2014 at 16:17
Add a ment  | 

2 Answers 2

Reset to default 4

Your JS is wrong:

Instead of GetElementById should be getElementById. Javascript is case sensitive.

And I don't see where do you have hide function declaration. I see only mouse function that is never used.

Also according to @Harry ment by calling getElementsByTagName you will get DOM elements collection. So you should use:

dog[ 0 ].addEventListener("click", hide, false);

lots of misspellings

//get not Get
var cat = document.getElementById("container");
//get first of array
var dog = cat.getElementsByTagName("button")[0];
function mouse (){
    alert("mouse")
};
//no hide function
dog.addEventListener("click", mouse, false);
发布评论

评论列表(0)

  1. 暂无评论