如何使用以下代码中的函数setSelected Currency()获取所选元素

问题描述 投票:-1回答:1

我正在构建一个货币转换器应用程序,我正在尝试使用我的代码中的getSelectedCurrency()函数选择货币。当我在我的代码中控制日志值时,它返回文本,但不满足返回所选货币的TDD测试

我尝试过使用事件监听器,但事件监听器通常会返回undefined

 // declare populateCurrencies here      
   const populateCurrencies = ()=>{
    currencies.forEach((x)=>{
      let elt = document.querySelector('.select-text');
      let newElt = document.createElement('option');
      let newText = document.createTextNode(x.name);
      newElt.appendChild(newText);
      newElt.setAttribute('value',x.id);
      elt.appendChild(newElt);
    })
      let elt = document.querySelector('.select-text');
    elt.addEventListener('change',()=>{
       let currentlySelected =document.querySelector('[selected]');
       currentlySelected.removeAttribute('selected');
       elt.selectedOptions[0].setAttribute('selected','');
      },false)
    }

   function getSelectedCurrency(){
    // here, determine and return the selected value 
    // of the SELECT element
    let currentlySelected= document.querySelector('.select-text');
    let value= currentlySelected.selectedOptions[0].text;
    return((String(value)));
  };
  const convert = (event) => {
    toast(`preparing to convert ...`);

    const btn = event ? 
          event.target : document.querySelector('button');

    const selected = getSelectedCurrency();
    console.log(selected);

    if(!selected || selected.trim() === '' 
       || !currencies.map(c => c.id).includes(selected)) return;

    btn.setAttribute('disabled', 'disabled');
    toast(`converting ...`);

    const endpoint = api(selected);

我希望getSelectedCurrency()返回一个字符串,但它什么都不返回。

javascript dom
1个回答
0
投票

您正在以错误的方式选择该选项

function getSelectedCurrency(){
    // here, determine and return the selected value 
    // of the SELECT element
    let currentlySelected= document.querySelector('.select-text');
    let value= currentlySelected.options[currentlySelected.selectedIndex].textContent;
    if(value="")
    return false;
    else
    return value;
  };
© www.soinside.com 2019 - 2024. All rights reserved.