On Nov 1, 2:21 pm, "Dan G. Switzer, II" <[EMAIL PROTECTED]>
wrote:
> >i've just started using jQuery, and I'm having lots of fun.
>
> >I have the following code snippet. What it does is looks for all
> >instances of a <td>true</td> and <td>false</td> and replaces the
> >content with an image of a tick and cross.
>
> >The snippet is
>
> >            $("td").each(function(){
> >                    if (this.innerHTML == 'true') {
> >                            this.innerHTML = '<img
> >src="$base/images/true.png">';
> >                    }
> >                    if (this.innerHTML == 'false') {
> >                            this.innerHTML = '<img
> >src="$base/images/false.png">';
> >                    }
> >            });
>
> >I would just like to throw it out there, is there a neater way of
> >using jQuery to perform the same function ? I tried
>
> >$("td:contains('true')")
>
> >, but the <td> can be nested, which causes the parent <td> to be
> >replaced.
>
> A couple of notes:
>
> 1) I'd try to use a more specific selector in order to reduce the number of
> possible matches. The number of cells in a table can quickly get very large,
> so parsing over every single <td> tag in a DOM can start to get slow. So, if
> your table looked like:
>
> <table id="features">
>         <tr>
>                 <td>Product X</td>
>                 <td class="boolean">true</td>
>         </tr>
>         <tr>
>                 <td>Product Y</td>
>                 <td class="boolean">false</td>
>         </tr>
> </table>
>
> I'd use a selector like: $("#features tr > td.boolean")
>
> This would limit the results to only the table cells with a class of
> "boolean". That will drastically reduce your match set.
>
> 2) I'd use the html() method instead of innerHTML. If you're going to use
> jQuery, take advantage of all it's cross browser goodness.
>
> So, the revised code might look something like:
>
> $("#features tr > td.boolean").each(function(){
>         // cache reference to current element as a jQuery object
>         var $el = $(this);
>         // get the trimmed value in the cell
>         var sValue = $.trim($el.html());
>         // if the value is true or false, then replace the content with
> image
>         if( sValue == "true" || sValue == "false" )
>                 $el.html('<img src="$base/images/' + sValue + '.png" />');
>
> });
>
> -Dan

There's some room for optimization, why not leave away the if
condition if the value is always true or false and the value is
inserted as-is anyway:

var $td = $("#features td.boolean"), value = $.trim($td.text());
$td.html('<img src="$base/images/' + value + '.png" alt="' + value +
'" />');

I added the missing alt attribute, because that td must always be a
child of a row I think the selector can be simplified a bit as well.
Maybe the text() method does an trim already, not sure...



--Klaus

Reply via email to