繁体   English   中英

Javascript从数组列表中获取特定值

[英]Javascript get specific values from array list

<select name="List" id="List">
    <option value="">-Select-</option>
    <option value="">--Product--</option>
    <option value="">product1</option>
    <option value="">product2</option>
    <option value="">product3</option>
    <option value="">--Software--</option>
    <option value="">software1</option>
    <option value="">software2</option>
    <option value="">software3</option>
    <option value="">--Services--</option>
    <option value="">service1</option>
    <option value="">service2</option>
    <option value="">service3</option>
</select>

我的 HTML 选择字段中有上述列表。

我希望能够只获得值 --Product--、--Software--、--Services-- 所以我创建了一个循环来抛出产品列表并使用方法 startwith 来获取以“——”。

function loadFilter() {
  var x = document.getElementById('List');
  var i;
  var n;
  for (i = 0; i < x.length; i++) {
    str = x[i].text
    var n = str.startsWith('--');
    flag = true;
    if (n == true) {
      alert(x[i].text);   // list --Product--, --Software--, --Services--
      alert(x[3].text);   // prints from the LIST <product1> and not <--Services-->
    }
  }
}

所以当标志为真时, alert(x[i].text); 正确列出值(--Product--、--Software--、--Services--)。

但是当我尝试通过它们的值(索引)获取它们时,EG ..我只需要获取 (--Services--),所以我使用x[3].text) ,但这会返回整个列表值> > 而不是 <--Services-->。

您可以使用以下代码用带有“--”的选项列表填充数组arr

然后你可以使用arr[2]来获取--Services--

 var arr = []; [].slice.call(document.querySelectorAll("#List option")).map(function(el){ if (el.text.indexOf("--") === 0) arr.push(el.text); }); console.log(arr) console.log(arr[2])
 <select name="List" id="List"> <option value="">-Select-</option> <option value="">--Product--</option> <option value="">product1</option> <option value="">product2</option> <option value="">product3</option> <option value="">--Software--</option> <option value="">software1</option> <option value="">software2</option> <option value="">software3</option> <option value="">--Services--</option> <option value="">service1</option> <option value="">service2</option> <option value="">service3</option> </select>

我仍然不完全确定你想要做什么。 --Services-- 是索引 9,而不是 3。要获得 --Services-- 你需要x[9].text

如果要将这三个 --xx-- 重新排列为它们自己的索引,则需要将它们推送到一个新数组中,如下所示:

var output = []
if (n === true) output.push(x[i].text)
console.log(output[2]) // --Services--

干得好:

function loadFilter() {
    var element = document.getElementById('List');
    var children = element.children;
    var filtered = [];
    for (var i = 0; i < children.length; i++) {
        if (children[i].textContent.startsWith('--')) {
            filtered.push(children[i].textContent);
        }
    }
    return filtered;
}

回顾一下该函数的作用:

  1. 获取元素“列表”
  2. 获取“列表”的孩子
  3. 创建一个数组来保存通过过滤器的元素
  4. 遍历每个元素并添加与指定正则表达式匹配的元素
  5. 返回通过过滤器的元素

您可以使用简单的 forEach 循环来像这里这样循环遍历元素,但首先您需要从 DOM 节点列表创建数组:

  var list = Array.from(x);
  list.forEach((value,index)=>{
    if (value.text.startsWith('--')){
      alert(value.text);
    }
  });

我已经把它放在小提琴上,所以你可以检查: https : //jsfiddle.net/pegla/qokwarcy/

首先,您根本没有看到使用您的标志。

如果我理解正确,您正在尝试使用x[3].text获取 --Services-- ,但是如果您计算整个列表,则索引 [3] 处的元素是 . 您可以使用以下代码进行验证:

f (n == true) {
  alert('index '+ i + ': ' + x[i].text);   // list --Product--, --Software--, --Services--
}

您可以创建一个包含过滤选项的新数组,然后使用已知索引访问:

var filteredArray = [];
f (n == true) {
  filteredArray.push(x[i]); //insert the element in the new array.
}
alert(filteredArray[2].text) //print --Service--, the third element of filtered array.

请记住,javascript 的索引数组为零,因此第一个元素的索引为 0,因此,为了访问第三个元素,您需要索引 2。

您可能想尝试使用optgroups吗?

像这样的东西:

<select name="List" id="List">

    <option value="">-Select-</option>

    <optgroup label="--Product--">
        <option value="">product1</option>
        <option value="">product2</option>
        <option value="">product3</option>
    </optgroup>

    <optgroup label="--Software--">
        <option value="">software1</option>
        <option value="">software2</option>
        <option value="">software3</option>
    </optgroup>

    <optgroup label="--Services--">
        <option value="">service1</option>
        <option value="">service2</option>
        <option value="">service3</option>
    </optgroup>

</select>

然后,

var select = document.getElementById('List');
var optgroups = select.getElementsByTagName('optgroup');

console.log(optgroups[2].label);

将会呈现:

--Services--

尝试:

 function load() { list = document.getElementById('List'); var data = document.getElementsByTagName('option'); currentCatagory=null;//the current selected catagory currentvalue=null; listdata=[]; //for all the options for(cnt = 0; cnt < data.length; cnt++){ var e = data[cnt].innerHTML;//get option text if(e.startsWith('-')){//test to make a catagory out of it if(currentCatagory!=null)//do not concat is listdata is null listdata=listdata.concat(currentCatagory); currentCatagory = {"this":e,"listOfItems":[]};//create the catagory }else if(currentCatagory!=null){//make sure currentCatagory is not null var l=currentCatagory.listOfItems;//get the Catagory's list currentCatagory.listOfItems = l.concat(e);//and add e } } listdata=listdata.concat(currentCatagory);//add last catagory //sets the list to show only catagories var inner=''; for (i = 0; i < listdata.length; i++) { inner+=parseOp(listdata[i].this); } list.innerHTML=inner; } function update(){ //check to make sure everything is loaded if(typeof list=='undefined'){ load(); } var inner='';//the new options var value=list.options[list.selectedIndex].innerHTML; if(value==currentvalue) return; if(value.startsWith('-')){//if catagory if(value.startsWith('--')){//if not -Select- for (i = 0; i < listdata.length; i++) {//for all catagories if(value==listdata[i].this){//if it is the current selected catagory then... currentCatagory=listdata[i];//update the currentCatagory object inner+=parseOp(listdata[i].this);//parse as option and append //then append catagory's items for(item in listdata[i].listOfItems){ inner+=parseOp(listdata[i].listOfItems[item]); } }else{//appends the other catagories inner+=parseOp(listdata[i].this); } } }else{//if it is '-select-' then just append the catagories for (i = 0; i < listdata.length; i++) { inner+=parseOp(listdata[i].this); } } //set the new options list.innerHTML=inner; } } function parseOp(str){ //parse the options return '<option value="">'+str+'</option>'; }
 <select name="List" id="List" onchange="update();"> <option value="">-Select-</option> <option value="">--Product--</option> <option value="">product1</option> <option value="">product2</option> <option value="">product3</option> <option value="">--Software--</option> <option value="">software1</option> <option value="">software2</option> <option value="">software3</option> <option value="">--Services--</option> <option value="">service1</option> <option value="">service2</option> <option value="">service3</option> </select>

并设置下拉框,您必须运行load()否则load()将仅在第一个更改事件发生后调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM