2012-11-23 43 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