Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery selector: delegate click event to only tr elements with specific data
    primarykey
    data
    text
    <p>I'm trying to delegate a click event to a TR element that contains a TD with a specific attribute, i.e.</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;product one&lt;/td&gt; &lt;td&gt;price&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td data-imgurl="images/p2.png"&gt;product two&lt;/td&gt; &lt;td&gt;price&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>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.</p> <p>My selector (that works only in that it will assign a click to the actual TD element:</p> <pre><code>$("table").delegate("tr td[data-imgurl]", "click", function(evt){ alert( $(this).attr("data-imgurl") ); }); </code></pre> <p>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.</p> <p>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.</p> <p><strong>EDIT</strong> Ok, I resolved this by pushing the data into the actual row itself. Makes more sense that way, each row is a record. Solution:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;product one&lt;/td&gt; &lt;td&gt;price&lt;/td&gt; &lt;/tr&gt; &lt;tr data-imgurl="images/p2.png"&gt; &lt;td&gt;product two&lt;/td&gt; &lt;td&gt;price&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>And the jQuery</p> <pre><code>$("table").delegate("tr[data-imgurl]", "click", function(evt){ alert( $(this).attr("data-imgurl") ); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload