Why is the code not working?

2

I want to, by means of a pure and simple script ), to alert after the click on a given link (from the " exit ") the following: "You are leaving the site".

My script looks like this:

window.document.querySelectorAll('.**sair**').onclick = function aviso() {
     alert('Você está saindo do site.');
}; 

The " exit " class is in the HTML markup section below:

<p><a href="http://www.google.com.br" title="www.google.com.br" class="botao sair">Google</a></p>

When I call link , it does not alert anything at all.

Note

I tried the script :

window.document.getElementsByClassName('sair').onclick = function aviso() {
    alert('Você está saindo da página.'); 
 };

And, it also did not work.

What's wrong ?!

Thanks in advance,

Alexandre Soares

    
asked by anonymous 19.06.2015 / 23:25

1 answer

1

If you have more than one link, I see that you are using querySelector All , so you have to use a for loop to add the event sink to each element. This is because querySelectorAll gives a list of elements (type Array ).

Something like this:

var links = document.querySelectorAll('.sair');
for (var i = 0; i < links.length; i++) {
    links[i].addEventListener('click', aviso);
}

function aviso(e) {
    alert('Você está saindo do site.');
};

jsFiddle: link

You can also use your syntax links[i].onclick = aviso; ( jsFiddle )

If you have only one element you have to use querySelector (without All ) and there your code already works , ie you do not need the for cycle.

    
19.06.2015 / 23:35