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

时间:2022-11-27 19:55:51

How do I split this string:

如何拆分此字符串:

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

...by ||?

Then, I'd like to create a select list like this:

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

<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 个解决方案

#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


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'
}));

Version with a bit more flexibility (and jQuery abilities): http://jsfiddle.net/j6DjR/

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

#3


2  

Preamble:

I used a <select> element with id and name attributes of "assorted". "options" is a terrible id/name for a form element. Read here for more: http://www.fortybelow.ca/hosted/comp-lang-javascript/faq/names/

我使用了一个


Code:

No mess, no fuss.

没有乱,没有大惊小怪。

(commonElements.testing is the form containing the <select> element)

(commonElements.testing是包含

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);

Working Link (with full code):

http://jsbin.com/ucajep

#4


2  

Try the following:

请尝试以下方法:

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);

#5


0  

Your problem is simple:

你的问题很简单:

  1. Split string, using || as separator.
  2. 拆分字符串,使用||作为分隔符。

  3. Loop over the splitted string.
    1. Create a new option element
    2. 创建一个新的选项元素

    3. Set its value and text to the current item
    4. 将其值和文本设置为当前项

    5. Add the element to containing select element
    6. 将元素添加到包含select元素

  4. 循环分裂的字符串。创建新选项元素将其值和文本设置为当前项将元素添加到包含select元素

Here's a simple implementation of it (without using jQuery). I use Array.prototype.forEach and element.textContent (the former being ES5 and latter being non-IE), but it should bring the point across (and they're not hard to shim).

这是一个简单的实现(不使用jQuery)。我使用Array.prototype.forEach和element.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' );

You can then manipulate selectElem just like you'd manipulate any other DOM element.

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

#6


-1  

You can split the string into an array, then iterate through the array building an HTML string that you can then append to the DOM:

您可以将字符串拆分为数组,然后遍历数组,构建一个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>');

Here's a jsfiddle to demonstrate: http://jsfiddle.net/jasper/eb5Dj/

这里有一个jsfiddle来演示:http://jsfiddle.net/jasper/eb5Dj/

#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


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'
}));

Version with a bit more flexibility (and jQuery abilities): http://jsfiddle.net/j6DjR/

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

#3


2  

Preamble:

I used a <select> element with id and name attributes of "assorted". "options" is a terrible id/name for a form element. Read here for more: http://www.fortybelow.ca/hosted/comp-lang-javascript/faq/names/

我使用了一个


Code:

No mess, no fuss.

没有乱,没有大惊小怪。

(commonElements.testing is the form containing the <select> element)

(commonElements.testing是包含

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);

Working Link (with full code):

http://jsbin.com/ucajep

#4


2  

Try the following:

请尝试以下方法:

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);

#5


0  

Your problem is simple:

你的问题很简单:

  1. Split string, using || as separator.
  2. 拆分字符串,使用||作为分隔符。

  3. Loop over the splitted string.
    1. Create a new option element
    2. 创建一个新的选项元素

    3. Set its value and text to the current item
    4. 将其值和文本设置为当前项

    5. Add the element to containing select element
    6. 将元素添加到包含select元素

  4. 循环分裂的字符串。创建新选项元素将其值和文本设置为当前项将元素添加到包含select元素

Here's a simple implementation of it (without using jQuery). I use Array.prototype.forEach and element.textContent (the former being ES5 and latter being non-IE), but it should bring the point across (and they're not hard to shim).

这是一个简单的实现(不使用jQuery)。我使用Array.prototype.forEach和element.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' );

You can then manipulate selectElem just like you'd manipulate any other DOM element.

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

#6


-1  

You can split the string into an array, then iterate through the array building an HTML string that you can then append to the DOM:

您可以将字符串拆分为数组,然后遍历数组,构建一个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>');

Here's a jsfiddle to demonstrate: http://jsfiddle.net/jasper/eb5Dj/

这里有一个jsfiddle来演示:http://jsfiddle.net/jasper/eb5Dj/