I’m trying to delegate a click event to a TR element that contains a TD with a specific attribute, i.e.
<table>
<tr>
<td>product one</td>
<td>price</td>
</tr>
<tr>
<td data-imgurl="images/p2.png">product two</td>
<td>price</td>
</tr>
</table>
The goal is to click on the row and retrieve that row’s TD “data-imgurl” attribute value, i.e. the URI for an image. This is just a test to retrieve that value. Ultimately I’d want to have the click handler show the image in a hidden DIV or maybe lightbox, not sure what I want to do yet.
My selector (that works only in that it will assign a click to the actual TD element:
$("table").delegate("tr td[data-imgurl]", "click", function(evt){
alert( $(this).attr("data-imgurl") );
});
Note, the data is created dynamically from a server-side script, and the “data-imgurl” attribute is based on logic in that script, so that only products that actually have images are assigned a “data-imgurl” attribute. Perhaps I’m looking at it all wrong, and should somehow attach the data to the row itself, but that is counter-intuitive.
Or maybe I should be actually pushing the image into a hidden TD and assigning it a class or rel attribute? So it exists on the page but then a click reveals it? The idea still being that only those products with actual images can be clickable.
EDIT
Ok, I resolved this by pushing the data into the actual row itself. Makes more sense that way, each row is a record. Solution:
<table>
<tr>
<td>product one</td>
<td>price</td>
</tr>
<tr data-imgurl="images/p2.png">
<td>product two</td>
<td>price</td>
</tr>
</table>
And the jQuery
$("table").delegate("tr[data-imgurl]", "click", function(evt){
alert( $(this).attr("data-imgurl") );
});
Yep, I’d push it onto the row. This data defines the product, which is represented by a row, not a cell.
Regardless, if you weren’t using
delegate, it would be easy to put the click event onto the row.With
delegate, however, things get messier, and I’m not immediately sure if one can do it that way.