从拆分字符串创建选择标记

时间:2011-11-30 17:50:19

标签: javascript jquery html string dom

如何拆分此字符串:

waterfowl||tvs||guitar||pillow||mouse

... ||

然后,我想创建一个这样的选择列表:

<select name="options" id="options">
  <option value="waterfowl">waterfowl</option>
  <option value="tvs">tvs</option>
  <option value="guitar">guitar</option>
  <option value="pillow">pillow</option>
  <option value="mouse">mouse</option>
</select>

6 个答案:

答案 0 :(得分:3)

// Turns a string in to a combo box based on:
// @d      Delimiter to split the string up by
// @so     Select box attributes (adding name="foo" means passing {name:'foo'})
// Result: jQuery object of the new select element, populated with the items
//         from the string
String.prototype.toSelect = function(d,so){
    so = so || {};

    var s = $('<select/>',so),
        items = this.split(d);
    for (var i = 0; i < items.length; i++){
        $('<option/>').val(items[i]).text(items[i]).appendTo(s);
    }
    return s;
}

// an example
// Append the following string to the body of the document
// after it's been converted in to  a <Select> element
$('body').append("waterfowl||tvs||guitar||pillow||mouse".toSelect('||',{
    name: 'select',
    id: 'select'
}));

具有更多灵活性(和jQuery能力)的版本:http://jsfiddle.net/j6DjR/

答案 1 :(得分:3)

var options = 'waterfowl||tvs||guitar||pillow||mouse';

$( '#someDiv' ).html( '<select name="options" id="options">'
    + options.replace(/(\w+)\|*/g, '<option value="$1">$1</option>')
    + '</select>' );

答案 2 :(得分:2)

尝试以下方法:

var input = 'waterfowl||tvs||guitar||pillow||mouse';
var split = input.split('||');
var select = $('<select name="options" id="options"></select>');
$.each(split, function(index, value) {
  var option = $('<option></option>');
  option.attr('value', value);
  option.text(value);
  select.append(option);
});
$('#idOfContainer').empty().append(select);

答案 3 :(得分:2)

序言:

我使用<select>元素,idname属性 “什锦”。 “options”是表单元素的可怕id /名称。 请阅读此处了解更多信息:http://www.fortybelow.ca/hosted/comp-lang-javascript/faq/names/


代码:

没有混乱,没有大惊小怪。

commonElements.testing是包含<select>元素的表单)

var commonElements =
{
    "testing": document.getElementById("testing"),
    "assorted": document.getElementById("assorted")
},
options = "waterfowl||tvs||guitar||pillow||mouse";

function addOptions (optionList)
{
    var i = 0,
    limit = optionList.length,
    parent = commonElements.assorted,
    option;
    for (i;i<limit;i++)
    {
        option = document.createElement(
            "option"
        );
        option.text = optionList[i];
        option.value = optionList[i];
        parent.add(option, null);
    }
}

function createOptions (toSplit)
{
    var optionList = toSplit.split("||");
    addOptions(optionList);
}

createOptions(options);

工作链接(带完整代码):

http://jsbin.com/ucajep

答案 4 :(得分:0)

你的问题很简单:

  1. 使用||拆分字符串作为分隔符。
  2. 循环分割的字符串。
    1. 创建新的option元素
    2. 将其值和文本设置为当前项
    3. 将元素添加到包含select元素
  3. 这是一个简单的实现(不使用jQuery)。我使用Array.prototype.forEachelement.textContent(前者是ES5,后者是非IE),但它应该引出一点(而且它们并不难以填充)。

    function makeSelect( options, separator ) {
        var select = document.createElement( 'select' ),
            optionElem;
    
        options.split( separator || '||' ).forEach(function( item ) {
    
            optionElem = document.createElement( 'option' );
    
            optionElem.value =
                optionElem.textContent =
                    item;
    
            select.appendChild( optionElem );
        });
    
        return select;
    }
    
    var selectElem = makeSelect( 'waterfowl||tvs||guitar||pillow||mouse' );
    

    然后,您就可以操纵selectElem,就像操纵任何其他DOM元素一样。

答案 5 :(得分:-1)

您可以将字符串拆分为数组,然后遍历数组,构建一个HTML字符串,然后将其附加到DOM:

var str = 'waterfowl||tvs||guitar||pillow||mouse',//the string to be split
    arr = str.split('||'),//the split string, each split stored in an index of an array
    out = '';//our output buffer variable

//iterate through each array index
for (var index; index < arr.length; i++) {

    //add this index to the output buffer
    out += '<option value="' + arr[index] + '">' + arr[index] + '</option>';
}

//add the HTML we've built to the DOM, you can also use `.append(<code>)` instead of `.html(<code>)` but if you are using an ID for your select element then you ant to make sure and replace the HTML
$('#container-element').html('<select name="options" id="options">' + out + '</select>');

这是一个证明:http://jsfiddle.net/jasper/eb5Dj/

的小提琴