簡體   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