开发者

need correct jquery selector

开发者 https://www.devze.com 2023-01-14 15:53 出处:网络
I would like to bind a function to this anch开发者_如何学运维or but cannot seem to get the selector right

I would like to bind a function to this anch开发者_如何学运维or 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>


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/


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.


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')
0

精彩评论

暂无评论...
验证码 换一张
取 消