0

I have this js code:

(function($, undefined) {
    $("a").click(function(event) { //or another elemtnt
        alert('Hello!');
    })
})(jQuery);

And of course link:

<a href="http://google.ru/" target="_blank">Google</a>

the JS code doesn't work, but if I change it to:

(function($, undefined) {
    $("*").click(function(event) {
        alert('Hello!');
    })
})(jQuery);

all works!

Liam
  • 22,818
  • 25
  • 93
  • 157
row248
  • 119
  • 8

3 Answers3

3

If you've put your JavaScript before the a node is loaded the effect will be something like you described. Try this instead:

$(function () {
    $("a").click(function(event) { //or another elemtnt
        alert('Hello!');
    })
});

This will invoke the anonymous function when the DOM tree is ready. Here is an example in JSFiddle.

When you use * as selector jQuery adds click handler to the html element, that's why you get the alert.

Minko Gechev
  • 23,174
  • 7
  • 57
  • 66
0

why don´t you try with document.ready?

$(document).ready( function (){
    $('a').click(function (){
        alert("a");
    });
});
-1

This is a possible solution:

$(document).ready(function() {
    // put all your jQuery goodness in here.
});

why don't you give an ID to it and select for $('#my-id') for setting the event?

ThiefMaster
  • 285,213
  • 77
  • 557
  • 610
redflag237
  • 222
  • 4
  • 16