0

As per my post earlier (How to select a span with multiple classes and placed inside an anchor?)

I had implemented it as per the suggested solution & it worked perfect until I had an additional scenario now.

Earlier suggested sol:

 $('span.c3.c4').not('.ignore_class).parents('a').click(function (e) { alert("clicked!"); }); 

But now I've another scenario where in I want to bind a click event to the anchor without having any span within it.

Anchor Def:

<a href="#">LINK_TEXT</a>

So, I've below code in place for this scenario.

$('a').not('.ignore_class').click(function (e) { alert("clicked!"); });

The issue I'm facing here is when I click on the anchor with span.. the click event on the anchor without span is fired.

Can anyone please help me resolvce this scenario? Thanks so much!!

Community
  • 1
  • 1
Evolving Techie
  • 159
  • 1
  • 3
  • 13

2 Answers2

0

What you probably want is to make sure you attach the events in the proper order, and on the event you want to give priority to (the more specific one), finish your function with:

e.stopPropagation();

This will prevent your more general events (i.e. events attached to all a) from firing after your more specific ones have fired.

Or, what's probably a simpler way to reason about this scenario, have a single event and just test which kind of link was clicked:

$('a').click(function()
{
   if ($(this).find('span.c3.c4').not('.ignoredClass').length > 0)
   {
      // event for special links with spans in them
   }
   else
   {
      // event for normal links
   }
});
Plynx
  • 11,341
  • 3
  • 32
  • 33
  • Even though I attach events in a the desired order, the issue is the click event on an anchor takes precendence. I cannot use e.stopPropagation as this is being done at a global level and I will not know which anchor was clicked (with or without span) unless I specify it explicitly within the jquery used for click event – Evolving Techie Jan 28 '13 at 20:26
  • One is being fired first, so `e.stopPropagation` should work. However, you may as well just test whether you have a qualifying `span` or not in a single event rather than dealing with this. `if ($(this).find('span.c3.c4').not('.ignoredClass').length > 0) { /*...*/ } else { /**/ }` You can attach this event to all `a` and it would probably be much easier to reason about this way. – Plynx Jan 28 '13 at 20:29
0

Filter out the a with span tags using :not with :has selectors

$('a:not(:has(span))').click(function(){

});

Then you can select the one's with spans like this

$('a:has(span)') // <-- you can also pass in your span class if you want

FIDDLE

It looks like your .ignoreclass is at the span level and not the anchor - using .not() only filters the elements in the current collection, which is all the anchors. So to use it that way you could do it like this

$('a').not('a:has(.ignore_class)')
wirey00
  • 33,517
  • 7
  • 54
  • 65