views:

67

answers:

2
<script>
    $(function(){
            $("a.a, a.b, a.c, a.d").click(function () {
             alert('Hi');
            });
    });
</script>

<a href="#" class="a button">Hi</a>

The above JQuery unfortunately doesn't work. Probably an easy fix, any ideas? I need it to be a multi-selector, but with a's that have multiple classes unfortunately don't work.

+2  A: 

You can also get there by registering it as a 'live' event that will match all future elements that fit the selector. Something like this:

<script type="text/javascript" language=javascript>
  $('a.a, a.b, a.c, a.d').live('click', function() {
    alert('Hi');
  });
</script>

That'll cover you for any future elements created that also match your requirements.

g.d.d.c
Although element wasn't created after page load, simply by using live, it is now working. Weird. Thanks for the suggestion.
James
Even if the element wasn't created after page load you're running into order of operations. Essentially, if your `<script>` tag is in the header, it's executed before your elements are rendered. jQuery provides a number of ways to work around this. The live method is one. Using `$(document).ready()` would be another. That'll actually delay execution of your code until after the DOM is rendered. Both can accomplish the same thing, though live will also work for dynamically created elements meeting the same criteria.
g.d.d.c
Thing is, document.ready is used in the production code, so it's a bit weird why this is occurring.
James
So it is. Do you encounter the trouble only in a specific browser, or does it exhibit in all browsers for you? Either way, live() is a great way to work around it, but that's definitely interesting.
g.d.d.c
A: 

My assumptions are that those pieces are located properly within a valid HTML document, that your link to a current version of the jQuery library is functional, that you're using a modern browser, and that you're using a tool like Firebug to watch for errors during the initial page load and during the click. With your exact code set up with these assumptions, it works fine for me.

Ken Redler