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

巧了我就是萌 提交于 2019-12-17 22:24:16

问题


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.


回答1:


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");



回答2:


I indent as if it were bracketed:

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



回答3:


How about:

$("#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()
);

I find that chaining, when used in moderation, can lead to better readability.




回答4:


Don't chain so much.

var newContent = objButton.parents("tr").clone();

newContent.find(".RowTitle").text("Row " + nAddCount)
newContent.find(".FundManagerSelect").attr("id", "FundManager" + nAddCount)
    .change(function() { ChangeFundRow() });
newContent.find(".FundNameSelect").attr("id", "FundName" + nAddCount);

$("#FundTable").append(newContent);

Less chaining, but it seems easier to read imo.



来源:https://stackoverflow.com/questions/1286829/is-there-a-preferred-way-of-formatting-jquery-chains-to-make-them-more-readable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!