0

私は次のコードを使用しています:

   $('#dataTable .select-topic')
        .click(function () {
            if ($(this).attr('data-list') == "N") {
                $(this).attr('data-list', 'Y')
                var topicSelectHtml = $('#TopicID')
                .clone()
                .find("optgroup:first").remove().end()
                .find("option[value$='**']").remove().end().html();
                $(this).html(topicSelectHtml);
                $(this).attr('data-clicked', 'Y')
            }
        })
        .change(function () {
            $(this).attr("title", $("option:selected", this).text());
            var type = $(this).attr('id').split('_')[1];
            updateField(entity, $(this), type);
        })

各行に選択があるため、数百行に適用されます。効率を上げるには、名前付き関数を作成し、それらをクリックアンドチェンジにアタッチする方がよいでしょう。もしそうなら、どうすれば上記のコードに対してこれを行うことができますか?

4

2 に答える 2

2

関数に名前が付けられているかどうかは、実際にはパフォーマンスに影響しません。ただし、関数の何百もの異なるインスタンスを作成してバインドするよりも、委任されたイベントハンドラーを一度作成して、それを親にバインドする方がよい場合があります。

$('#dataTable').on('click', '.select-topic', function() {
    if ($(this).attr('data-list') == "N") {
        $(this).attr('data-list', 'Y')
        var topicSelectHtml = $('#TopicID').clone().find("optgroup:first").remove().end().find("option[value$='**']").remove().end().html();
        $(this).html(topicSelectHtml);
        $(this).attr('data-clicked', 'Y')
    }
}).on('change', '.select-topic', function() {
    $(this).attr("title", $("option:selected", this).text());
    var type = $(this).attr('id').split('_')[1];
    updateField(entity, $(this), type);
});​

これは同じ要素のクリックを処理しますが、バインドされている関数は1つだけなので、パフォーマンスが向上します。

于 2012-08-03T03:16:15.577 に答える
0

匿名関数を名前付き関数に変更しても、とにかくパフォーマンスは向上しません。あなたが思うクリーンなスタイルを使用してください。

于 2012-08-03T03:11:33.103 に答える