0

我有一个字符串:

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

我已将实际值替换为 x、y 和 z

它由;然后分隔|

我想要的是

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

我不需要获得y价值。

不知道如何做到这一点!任何想法都会很棒!谢谢。

4

3 回答 3

5

您首先要在字符上拆分字符串,;以便拥有 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");
});
于 2012-07-10T13:41:00.587 回答
0

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

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;
}
于 2012-07-10T13:52:11.413 回答
0

你去: 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>');
});
​
于 2012-07-10T13:44:20.587 回答