Thursday, April 30, 2009

[jQuery] Re: How to reduce this code by chain them up?

Ah.. okay. so it's .html() that's messing me up.

Thanks Ricardo. My original way of querying the templateTable by
passing itself as a "context" was awkward, the way you did is much
more "fluent".

That helps me a lot not only in this particular example, but helped me
understand the chainability as well. I greatly appreciate your help!!

Thanks again.


On Apr 30, 1:01 pm, Ricardo <ricardob...@gmail.com> wrote:
> On Apr 30, 10:27 am, Liming <lmxudot...@gmail.com> wrote:
>
>
>
> > Hello,
>
> > I have a div ( id="rightheader")  and inside there is a table. The
> > following code replace all content of the table with empty space and
> > then remove the table header.
>
> > var $templateTable = $("div#rightheader").clone();
> > $("tbody > tr > td > div ", $templateTable).html("&nbsp");
> > $("thead",$templateTable).remove();
>
> > I feel it might be unnecessary, but I can't figure out how to chain up
> > the statements.
>
> > I tried
>
> > var $templateTable = $("div#rightheader")
> >                                  .clone()
> >                                 .("tbody > tr > td > div ").html("&nbsp")
> >                                 .("thead").remove();
>
> > Got an error
>
> > then tried
>
> >         var $templateTable = $("div#rightheader")
> >                                                                  .clone()
> >                                                                  .find("tbody > tr > td > div ").html("&nbsp")
> >                                                                  .find("thead").remove();
>
> > but that just doesn't produce anything.
>
> > Sorry, I'm a real beginner on JQuery, any pointer is greatly
> > appreciate it.
>
> > Thanks
>
> the html() method doesn't return an object, so it has to be last:
>
> $("div#rightheader").clone()
>     .find("thead").remove().end()
>     .find("tbody > tr > td > div ").html("&nbsp");
>
> In this case I'd say chaining makes it more confusing, as you're
> copying/destroying elements on the way, not just traversing it. It's
> just a line shorter than this, which will be much clearer as I assume
> you're further modifying $templateTabe later:
>
> var $templateTable = $("div#rightheader").clone();
>
> $templateTable
>     .find("thead").remove().end()
>     .find("tbody > tr > td > div ").html("&nbsp");

No comments: