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
Post a Comment