簡體   English   中英

我如何使getSelectedCurrency僅在使用選項填充了select元素時運行

[英]How do I make getSelectedCurrency run only when the select element has been populated with options

我試圖從getSelectedCurrency函數返回當前選擇的選項,默認情況下,選擇貨幣選項被選中但被禁用。 現在,我試圖使函數僅在select元素中還有其他選項並且select元素更改時才返回當前選擇的選項。

我嘗試添加一個onchange事件偵聽器,但由於事件偵聽器默認情況下未定義返回值,因此我無法向該函數本身返回任何內容,因此在調用getSelectedCurrency ,它什么都不返回,這不是我想要的。

我還嘗試將onchange事件偵聽器添加到populateCurrencies函數,以便足夠早地注冊該事件。...但是當我在聲明它之后(並且在聲明populateCurrencies()之后getSelectedCurrency()調用getSelectedCurrency() )時,它僅返回默認值(即選擇貨幣文字)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>Mini App</title>

    <style>
        body{
            background-color:#fff;
            margin:15px;
            }
       .select{
            margin-top:50px;
        }
       .conversion{
            margin:25px 0px;
        }
       .btn{
            width:100%;
            font-size:1.2rem;
            padding:1rem;
           }
    </style>
</head>
<body>
    <h1>Naira Converted</h1>
    <div class="select-currency select">
        <select class="select-text">
            <option selected disabled>Select Currency</option>
        </select>
        <button type="submit" class="btn">In Naira</button>
        <div class="conversion mdc-elevation--z3"></div> 
        <div class="messages"></div>
    </div>
<script>
const currencies = [{
    id: 'USD', name: 'US Dollars'
  }, {
    id: 'UGX', name: 'Ugandan Shillings'
  }, {
    id: 'KES', name: 'Kenyan Shillings'
  }, {
    id: 'GHS', name: 'Ghanian Cedi'
  }, {
    id: 'ZAR', name: 'South African Rand'
  }];

  const apiBase = 'https://free.currencyconverterapi.com/api/v6/';
  const api = (currency) => `
    ${apiBase}convert?q=${currency}_NGN&compact=ultra
  `;

  const toast = (msg) => {
    const toastr = document.querySelector('.messages');
    if(!toastr) return;

    toastr.textContent = msg;
    if(!toastr.classList.contains('on')) {
      toastr.classList.add('on');
    }
  };

  const doneToasting = () => {
    const toastr = document.querySelector('.messages');
    if(!toastr) return;

    toastr.textContent = '';
    toastr.classList.remove('on');
  };

  const conversionSucceeded = (apiResponse) => {
    if(!apiResponse) {
      toast(`nothing to display ...`);
      return;
    }

    const [value] = Object.values(apiResponse)

    const btn = document.querySelector('button');
    btn.removeAttribute('disabled');

    const display = document.querySelector('.conversion');
    const formatter = new Intl.NumberFormat(
      'en-NG', { style: 'currency', currency: 'NGN' }
    );

    display.textContent = formatter.format(value);
    doneToasting();
  };
 // 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','');
      console.log(getSelectedCurrency());
      },false)
    }
   const getSelectedCurrency=()=>{
    // here, determine and return the selected value 
    // of the SELECT element
    let currentlySelected= document.querySelector('.select-text');
    let value= currentlySelected.selectedOptions[0].textContent;
    return(value) ;
  };
  const selected = getSelectedCurrency();
  console.log(selected);
  const convert = (event) => {
    toast(`preparing to convert ...`);

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

    const selected = getSelectedCurrency();

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

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

    const endpoint = api(selected);

    // make a GET fetch call to the endpoint
    // variable declared above, convert the response to JSON,
    // then call conversionSucceeded and pass the JSON data to it
  };

  const startApp = () => {
    // call populateCurrencies here
    populateCurrencies();
    // add a click listener to the button here
    document.querySelector('button').addEventListener('click',(event)=>       
    {convert(event)},false);
  };
  startApp();
        </script>
     </body>
</html>

我希望調用getSelectedCurrency應該返回當前選擇的選項,並且當發生更改時,它也應該返回該更改,但它只返回默認值。

在這里做了大量的整理工作,您多次選擇了控件,並且還獲得了text或您select而不是轉換value

現在可以開始添加API調用代碼了。

 const currencies = [{ id: 'USD', name: 'US Dollars' }, { id: 'UGX', name: 'Ugandan Shillings' }, { id: 'KES', name: 'Kenyan Shillings' }, { id: 'GHS', name: 'Ghanian Cedi' }, { id: 'ZAR', name: 'South African Rand' }]; const apiBase = 'https://free.currencyconverterapi.com/api/v6/'; const api = (currency) => `${apiBase}convert?q=${currency}_NGN&compact=ultra`; const toast = (msg) => { const toastr = document.querySelector('.messages'); if (!toastr) return; toastr.innerText = msg; toastr.classList.add('on'); }; const doneToasting = () => { const toastr = document.querySelector('.messages'); if (!toastr) return; toastr.innerText = ''; toastr.classList.remove('on'); }; const conversionSucceeded = (apiResponse) => { if (!apiResponse) { toast(`nothing to display ...`); return; } const [value] = Object.values(apiResponse) const btn = document.querySelector('button'); btn.removeAttribute('disabled'); const display = document.querySelector('.conversion'); const formatter = new Intl.NumberFormat( 'en-NG', { style: 'currency', currency: 'NGN' } ); display.innerText = formatter.format(value); doneToasting(); }; // declare populateCurrencies here const populateCurrencies = () => { let elt = document.querySelector('.select-text'); currencies.forEach((x) => { let newElt = document.createElement('option'); newElt.text = x.name; newElt.value = x.id; elt.add(newElt); }) elt.addEventListener('change', () => { console.log(getSelectedCurrency()); }, false) }; const getSelectedCurrency = () => { // here, determine and return the selected value // of the SELECT element let currentlySelected = document.querySelector('.select-text'); let value = currentlySelected.selectedOptions[0].value; return (value); }; const selected = getSelectedCurrency(); console.log(selected); const convert = (event) => { toast(`preparing to convert ...`); const btn = event ? event.target : document.querySelector('button'); const selected = getSelectedCurrency(); toast(`converting for currency: ${selected}`); if (!selected || selected.trim() === '' || !currencies.map(c => c.id).includes(selected)) return; btn.setAttribute('disabled', 'disabled'); toast(`converting ...`); const endpoint = api(selected); // Need to add your API call now. console.log(endpoint); // make a GET fetch call to the endpoint // variable declared above, convert the response to JSON, // then call conversionSucceeded and pass the JSON data to it }; const startApp = () => { // call populateCurrencies here populateCurrencies(); // add a click listener to the button here document.querySelector('button').addEventListener('click', (event) => { convert(event) }, false); }; startApp(); 
 body { background-color: #fff; margin: 15px; } .select { margin-top: 50px; } .conversion { margin: 25px 0px; } .btn { width: 100%; font-size: 1.2rem; padding: 1rem; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Mini App</title> </head> <body> <h1>Naira Converted</h1> <div class="select-currency select"> <select class="select-text"> <option selected disabled>Select Currency</option> </select> <button type="submit" class="btn">In Naira</button> <div class="conversion mdc-elevation--z3"></div> <div class="messages"></div> </div> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM