javascript - querySelectorAll not working? -


this javascript code:

function answer(){ var list = document.queryselectorall("#fish"); list[1].onclick = talk(); }  function talk(){ alert('hello!'); }  window.onload = answer(); 

on run pops browser window alert: 'hello'. html code:

<!doctype html> <html> <head> <title>my site</title> <script src="new 3x.js"></script> </head> <body> <section> <p id="fish">hello world!</p> <p id="fish">tuna</p> <p id="stuff">durr</p> </section> </body> </html> 

it alerts hello on loading tab.whereas want run alert when click tuna!

you're not assigning event handlers correctly - you're assigning result of invoking functions, rather functions themselves. remove ()s:

function answer(){ var list = document.queryselectorall("#fish"); list[1].onclick = talk; }  function talk(){ alert('hello!'); }  window.onload = answer; 

what's happening that, window.onload = answer(); line hit, you're running answer function. it, in turn when reaches onclick line, invoking talk function. that's not wanted.


Comments

Popular posts from this blog

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

android - How to create dynamically Fragment pager adapter -

1111. appearing after print sequence - php -