1

我正在编写一个插件,用我用 html/css 制作的另一个插件替换原来的插件,简而言之,一个选择框。

我有性能问题,我承认我的代码相当繁重。首先,我获取每个选择的 ID,然后在 HTML 代码之后添加一些 CSS 参数,例如宽度、位置...

$(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

4

1 回答 1

1

小而简单的改进,缓存 $(this) 并最小化 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);
于 2012-11-23T10:03:21.517 回答