搜索克隆选择对象以获取选项值,并设置选中(如果存在)

时间:2014-08-21 21:12:56

标签: javascript jquery select drop-down-menu jquery-selectors

我尝试做的是克隆模板选择下拉元素,将其改变一些属性,然后查看字符串是否作为选项值存在,如果存在,则继续在我追加它之前预先选择该选项值。

/* Generated HTML inputs for mapping */
    function build_map_input( col_name ) {

        var select = jQuery("#leads_map").clone();

        /* alter dropdown attributes */
        select.attr( 'id' , col_name );         
        select.attr( 'style' , '' );            
        select.attr( 'name' , col_name );   

        /* attempt to preselect values if applicable */
        /*** This is where I need help. My needle is col_name ****/

        var select_html = select.prop('outerHTML');;

        /* build html */
        var html= '<div class="row">';
        html += '   <div class="col-md-3">';
        html +=         col_name;
        html += '   </div>';
        html += '   <div class="col-md-3">';
        html +=         select_html;
        html += '   </div>';
        html += '</div>';

        /* append html to map container */
        jQuery('#map-container').append(html);


    }

1 个答案:

答案 0 :(得分:1)

我在我的电脑上尝试了你的代码并且它运行良好。不过我建议这个代码:

/* build html */
var html= '<div class="row">';
html += '   <div class="col-md-3">';
html +=         col_name;
html += '   </div>';
html += '   <div class="col-md-3">';
html +=         select_html;
html += '   </div>';
html += '</div>';

替换为这个:

var html = $('<div/>', { class: "row" });
$('<div/>', { class: "col-md-3", text: col_name }).appendTo(html);
$('<div/>', { class: "col-md-3", html: select_html }).appendTo(html);

通过这种方式,阅读代码将非常简单。

你也可以使用$ mark而不是jQuery。

相关问题