tags:

views:

42

answers:

3

I would like to bind a function to this anchor but cannot seem to get the selector right

This didn't work

$(function(){
$("a[onclick=='RemoveCCard_OnClick(event);']").bind('click', function() {
alert("");
return false;
});
});



<span style="display: block;" id="span_remove_selected_ccards">
<a style="color: rgb(153, 153, 153);" onclick="RemoveCCard_OnClick(event);" href="javascript: void(0);">
<span class="PageText_L31n">remove selected</span></a>
<input type="hidden" value="1968" name="remove_ccardid" id="remove_ccardid">
</span>
+3  A: 

There should be only one '=' as you are using the Attribute Equals Selector:

$("a[onclick='RemoveCCard_OnClick(event);']").bind('click', function() {
    alert("");
    return false;
});​

Demo: http://jsfiddle.net/ucHuY/

karim79
A: 

Don't use the attribute selector like that. If you need to attach an event handler to a specific element, give it a class or, if it is unique, an id, like so:

<a id="unique" href="#">Look ma, I'm special!</a>
<a class="many" href="#">You can have lots and lots of me with the same class here</a>

Then use the following selectors to select them

$('#unique')
$('.many')
Yi Jiang
That did not answer my question at all. I do not have access to that markup or I would have put an id in the anchor.
+1  A: 

I would suggest a much simpler selector here not looking at an onclick attribute, like this:

$("#span_remove_selected_ccards > a").click(function() {
  return false;
});

This uses an #ID selector on the parent element then gets the > (immediate child) <a> to bind the event to. .click() is just a shortcut for .bind('click') when pass a function. Also, descending from an ID selector is much faster than looking for an attribute, which will crawl all anchors in the page.

Nick Craver
As always Nick you are right on target. I tried something similar and it didn't work $("span#span_remove_selected_ccards > a"). Perhaps I did something wrong. Anyway your selector worked great, thanks!