Jquery binds to multiple anchors

I would like to associate the same event with a binding list. Why is this not working?

Markup:

<a tabindex="0" href="#contactRoles" class="fg-button fg-button-icon-right ui-widget ui-state-default ui-corner-all" id="contactAdd"> <span class="ui-icon ui-icon-triangle-1-s"></span>Aggiungi contatto</a> <div id="contactRoles" class="hidden"> <ul> <li><a href="#1" class="contactRole">Cliente</a></li> <li><a href="#2" class="contactRole">Controparte</a></li> <li><a href="#3" class="contactRole">Avvocato</a></li> <li><a href="#4" class="contactRole">Avv. Controparte</a></li> <li><a href="#5" class="contactRole">Altre parti</a></li> <li><a href="#6" class="contactRole">Domiciliatario</a></li> <li><a href="#7" class="contactRole">Pubblico Ministero</a></li> <li><a href="#8" class="contactRole">Giudice</a></li> <li><a href="#9" class="contactRole">Istruttori</a></li> <li><a href="#10" class="contactRole">Studio Legale</a></li> </ul> </div> 

JQuery

 $('#contactAdd').menu({ content: $('#contactRoles').html(), width: 150, showSpeed: 300 }); $("a.contactRole").click(function(event){ event.preventDefault(); alert("Link " + $(this).attr("href") + " clicked"); }); 

Where am I mistaken?

EDIT: @everybody: Yes the script is wrapped in a $ (document) .ready (...) document

For more information, think that a div with the "hidden" class is hidden and can only be viewed by clicking on another anchor, as you can see in this screenshot. alt text

+4
source share
3 answers

EDIT:. Based on your comment, you are already wrapped with the ready() function.

Another possibility is that a.contactRole elements a.contactRole added to the DOM after the page loads.

If this happens, try the following:

 $(function() { $("a.contactRole").live('click', function(event){ event.preventDefault(); alert("Link " + $(this).attr("href") + " clicked"); }); }); 

Original answer:

Must work. Make sure the document is loaded before assigning a click handler?

If the <a> elements are not loaded when trying to assign a handler, this will not work.

Example: http://jsfiddle.net/kjSG8/

  // Wrap your code with $(function() {...}) to make sure it doesn't // run until the DOM is fully loaded $(function() { $("a.contactRole").click(function(event){ event.preventDefault(); alert("Link " + $(this).attr("href") + " clicked"); }); }); 
+3
source

This seems to be a standard event, whether you declare it in the $(document).ready(function() { }); block $(document).ready(function() { }); ?

0
source

Make sure you create the click when the DOM is ready. You could just say $(".contactRole").click instead of $("a.contactRole").click

0
source

All Articles