2012-11-23 44 views
1

我正在寫一個插件,以用html/css替代原來的另一個插件,用幾句話,一個選擇框。提高jquery插件性能

我有perfomance的問題,我承認我的代碼它相當重。 起初,我把每一個選擇的ID和我一起的寬度,位置一些CSS PARAMS的HTML代碼後加...

$(this).after("<div class="selectbox" s-id='"+$(this).attr("id")+"'> the code of the select </div>"); 

然後,我隱藏了選擇和來這裏的第一部分認爲是相當重的,我拿的這一切選擇和我做這個

var selectbox=$("div[s-id="+selectID+"]"); //This is the div previously added after. 

//each option of the select will be converted into a div 
$.each($(this).find("option"), function(i) { 
    var valor = $(this).val(), 
     texto = $(this).text(); 

    if (i == 0) 
     selectbox.find(".class_valor").text(texto);//The first option to be shown 

    //Then I add a li to my drop 
    selectbox.find("ul").append('<li data-value="'+valor+'">'+texto+'</li>'); 
}); 

和好,現在,我不知道這是否是事件添加到打開的下拉菜單和觸發器的最佳途徑點擊一個選項,這不在選擇框功能裏面,它在(function($){之內

下面是代碼: http://codepen.io/anon/pen/kcpxl

+0

我想這可以通過[代碼點評網站]得到更好的服務( http://codereview.stackexchange.com/) – Sparky

+0

也許,但我也寫在這裏,因爲我也問最好的方法來做插件等事件,所以它不只是一個審查 – jsertx

+1

首先你應該縮小你的js插件,我認爲 – sbaaaang

回答

1

體積小,易於改進,緩存$(本),並儘量減少DOM操作

var selectbox=$("div[s-id="+selectID+"]"); //This is the div previously added after. 

    //each option of the select will be converted into a div 
    $.each($(this).find("option"), function(i) { 
     var $this = $(this), 
      valor = $this.val(), 
      texto = $this.text(), 
      liElems = ''; 

     if (i == 0) 
      selectbox.find(".class_valor").text(texto);//The first option to be shown 

     //Then I add a li to my drop 
     liElems += '<li data-value="'+valor+'">'+texto+'</li>'; 
    }); 

    selectbox.find("ul").append(liElems); 
+0

這很好,謝謝!那麼事件呢? – jsertx