How to bind an event to a group of links in the requested AHAH HTML
I have AHAH-requested HTML like:
<table>
<tr>
<td>...</td>
<td><img src="..." onClick="get_next_ahah(sell####)" id="sell####"/></td>
</tr>
<tr>
<td>...</td>
<td><img src="..." onClick="get_next_ahah(sell####)" id="sell####"/></td>
</tr>
... and so on
where #### are numeric identifiers from the database. How can I replace the " get_next_ahah()
" function with an efficient jQuery function written in the event? And how can I know which ID I am using?
You can use a rather obscure form of CSS selector to grab all elements whose ID contains the text "sell" and then use that to assign events to them:
$("[id^=sell]")
Or, if all elements are guaranteed to be img
s, you can use this more specific selector:
$("img[id^=sell]")
These selectors will return an array of items that "sell" in an identifier, which you can call click()
on.
To find out the current ID, you can simply remove the "sell" from the ID and then pass it to your function get_next_ahah()
, like this:
$("img[id^=sell]").click(function() {
get_next_ahah(this.id.replace('sell', '');
});
source to share
It would be easier to extract the number from the ID if you split the number from the prefix string by an underscore or something like this:
<img src="..." id="sell_1234"/>
Then you just need to do this:
$('table tr td img').click(function() {
var num = $(this).attr('id').split('_')[1];
get_next_ahah(num);
});
If you cannot change the identifier, just use a regex instead to extract the number from the string, e.g .:
$('table tr td img').click(function() {
var num = $(this).attr('id').match(/\((\d+)\)/)[1];
get_next_ahah(num);
});
source to share