0

私はJQueryとJSでこのような関数を持っています。チェックボックス付きのdivのリストがあり、それらをリストに追加しています。これは40divのように正常に機能しますが、2,000を持っていると、Chromeがクラッシュし、FFでクロールすることがあります。とにかくこれを速くするために?

function AddToList()
{
    $('div[name="notadded"] input:checked').each(function(index)
    {
        var html = $(this).parents('div[name="notadded"]').html();

        //get rid of the class that is used to gather checkboxes in select/deselect
        html = html.replace('listvars', 'addedvars');

        var var_id = $(this).attr('value');

        var new_html = '<div id="added_' + var_id + '" name="added">' + html + '</div>';

        //hide the one we are adding and remove the check
        $(this).parents('div[name="notadded"]').hide();
        $('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);

        //add the vars to the added list
        $('.addedList').append(new_html);

        step3 = '3b';
    });
}
4

1 に答える 1

2

あなたは2000のDOM操作を行っていますが、これは良い方法ではありません。2,000の文字列操作と1つのDOM挿入を実行しようとしています。

function AddToList()
{
    var new_html = "";

    $('div[name="notadded"] input:checked').each(function(index)
    {
        var html = $(this).parents('div[name="notadded"]').html();

        //get rid of the class that is used to gather checkboxes in select/deselect
        html = html.replace('listvars', 'addedvars');

        var var_id = $(this).attr('value');

        var new_html += '<div id="added_' + var_id + '" name="added">' + html + '</div>';

        //hide the one we are adding and remove the check
        $(this).parents('div[name="notadded"]').hide();
        $('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);

        //add the vars to the added list   
        step3 = '3b';
    });

    $('.addedList').append(new_html);
}

また、経験上、2,000個のチェックボックスをオフにすると、パフォーマンスが大幅に低下します。私はこのラインを取り出して賭けます:

$('div[name="notadded"] input[value="' + var_id + '"]').attr('checked', false);

すべてを変更します。この関数を文字列の置換として書き直すことをお勧めします。そうすれば、はるかに高速になります。

于 2012-07-19T20:02:33.927 に答える