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

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -