Skip to content Skip to sidebar Skip to footer

Where Is This JQuery Wrong?

I want to add the click event to all elements where the `id='violacao': $(document).ready(function () { jQuery('#violacao').click(function() { alert('teste'); }); }

Solution 1:

IDs in HTML are meant to be unique (one per document). Change the ID to a class (and use . instead of #) and it should work.


Solution 2:

While what Steve Mason says it's true, the actual problem is not that.

If you change ID to a class a problem persists: all links will get affected.

Instead, if you aim to affect one single <A>, you should do one of the following:

a) Assign unique IDs to each <A>, then do something like you were doing first; or

b) Assign classes and use the :first selector:

jQuery("a.violacao:first").click( function (){
  alert('teste');
} );

That will apply to the first matching anchor with class violacao. Alternatively, if you want to affect a specific anchor, you could use :eq(index).

For a comprehensive list of selector, visit http://docs.jquery.com/Selectors.


Post a Comment for "Where Is This JQuery Wrong?"