从指定的字符串中读取数据以创建选择元素

Reading data from delimted string to create a select element

本文关键字:数据 创建 选择 元素 读取 字符串      更新时间:2023-09-26

我有一个字符串:

x|y|z;x|y|z;x|y|z;x|y|z;

我已经用x,y和amp;z

它由;| 界定

我想要的是

<select>
    <option>x z</option>
    <option>x z</option>
    <option>x z</option>
    <option>x z</option>
</select>

我不需要获取y值。

不知道怎么做!任何想法都会很棒!谢谢

您首先想要在;字符上拆分字符串,这样您就有了xyz组合的数组:

var arr = str.split(";");
arr.pop(); // remove the last item:
           // your example has a trailing `;` which adds an empty item

然后,您需要拆分|字符上的每个组合,以便获得单独的xyz值。然后可以使用这些值来创建<option>元素。

// loop the array
$.each(arr, function() {
  var values = this.split("|");
  // ignore values[1], that's the y value
  $("<option>").text(values[0] + " " + values[2]).appendTo("select");
});

好了:http://jsfiddle.net/bfRyW/希望它能有所帮助!

var string = 'x|y|z;x|y|z;x|y|z;x|y|z;';
var split1 = string.split(';');
split1.pop();
$.each(split1,function(index,value){
    var a = value.split('|');
    $('select').append('<option>'+a[0]+' '+a[2]+'</option>');
});
​

使用一个正则表达式在|y|;上进行拆分的POJS解决方案是:

function genSelect(s) {
  var arr = s.split(/'|y'||;/);
  var sel = document.createElement('select');
  var t;
  for (var i=0, iLen=arr.length; i<iLen; i++) {
    t = arr[i] + ' ' + arr[++i];
    sel.appendChild(new Option(t, t));
  }
  return sel;
}