bind a click event and pass href attribute to a function
I have the following links (buttons) on a page that I need to instead of it going to the link to call a function instead and pass the url of the respective button clicked via a variable to that function. There may be more than 3 links (buttons) on the page but they all need to call the same function but pass the respective href valve of the button clicked on. My assumption is I need to do a bind of some sort but not really sure how to do it in jquery. Any help would be appreciated!!!
Edit: Unfortunately there are no id's for any of the anchors but the only way I can say to target the anchors is the begining of the href attribute which will always start with "/ShoppingCart.asp?ProductCode="
<td width="36%" align="right">
<a href="/ShoppingCart.asp?ProductCode=884280">
<IMG SRC="/v/vspfiles/temp开发者_高级运维lates/100/images/buttons/btn_addtocart_small.gif" ALIGN=absmiddle BORDER=0></A>
</td>
<td width="36%" align="right">
<a href="/ShoppingCart.asp?ProductCode=9857%2D116%2D003">
<IMG SRC="/v/vspfiles/templates/100/images/buttons/btn_addtocart_small.gif" ALIGN=absmiddle BORDER=0></A>
</td>
<td width="36%" align="right">
<a href="/ShoppingCart.asp?ProductCode=70367301P">
<IMG SRC="/v/vspfiles/templates/100/images/buttons/btn_addtocart_small.gif" ALIGN=absmiddle BORDER=0></A>
</td>
You can do this with jQuery pretty easily.
Let's create a sample function:
function someFunction(href) {
//do something with url
alert(href);
}
And then in jQuery, you can easily pass the href attribute to the function:
To get all elements starting with that prefix, simply use this code.
$("a[href^='/ShoppingCart.asp?ProductCode']").click(function () {
var href = $(this).attr('href');
someFunction(href);
return false;
});
The return false will prevent the link from going to that page.
精彩评论