Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

javascript - Is there a preferred way of formatting jQuery chains to make them more readable?

Given this following sample code which clones a table row, sets some properties and then appends it to a table:

$("#FundTable").append(
    objButton.parents("tr").clone()
        .find(".RowTitle").text("Row " + nAddCount).end()
        .find(".FundManagerSelect").attr("id", "FundManager" + nAddCount)
                                .change(function() { ChangeFundRow(); }).end()
        .find(".FundNameSelect").attr("id", "FundName" + nAddCount).end()
);

Does anyone have any suggestions as to how this might be formatted to be easier on the eye? Is there any accepted convention for doing this?

It would be useful to have a set of rules that can be followed, and that can be incorporated into a set of standards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would refactor to this. I find more than 3 chained methods uneasy on the eye

       var $clonedRow =  objButton.parents("tr").clone();

       $clonedRow.find(".RowTitle") 
                 .text("Row " + nAddCount);

       $clonedRow.find(".FundManagerSelect")
                 .attr("id", "FundManager" + nAddCount)
                 .change( ChangeFundRow );

       $clonedRow.find(".FundNameSelect")
                 .attr("id", "FundName" + nAddCount);

       $clonedRow.appendTo("#FundTable");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...