dpes8693 / frontend-mentor-program-1rd

前端培訓
0 stars 1 forks source link

蔡昆澤_HW7、Question #59

Open KunTsai opened 2 months ago

KunTsai commented 2 months ago

網頁連結: https://kuntsai.github.io/fetch/

Question: 在主畫面的程式碼中,有一行:

const countrySelect = document.getElementById('selectCountry');

已經設定一個變量countrySelect作為下拉式選單內容了,那為何GPT提供跳轉頁面的程式碼中還需要有:

countrySelect.addEventListener('change', () => {
            const selectedCountry = countrySelect.value;
            if (selectedCountry) {
                window.location.href = `country.html?name=${selectedCountry}`;
            }
        });

把countrySelect包裝成countrySelected作為'已選擇'的內容,而不能沿用countrySelect進行後續動作? 我的猜測是countrySelect已經作為變數在前面的函數使用過了,要進行到跳轉至查詢國家簡介的頁面時就得轉交給下一個變量才能用於下一個頁面的JS內容,不知道正不正確?

dpes8693 commented 2 months ago
dpes8693 commented 2 months ago

把countrySelect包裝成countrySelected作為'已選擇'的內容,而不能沿用countrySelect進行後續動作? 我的猜測是countrySelect已經作為變數在前面的函數使用過了,要進行到跳轉至查詢國家簡介的頁面時就得轉交給下一個變量才能用於下一個頁面的JS內容,不知道正不正確?

其實也可以不宣告,會變成以下(GPT就單純只是把一樣value抽出共用)


countrySelect.addEventListener('change', () => {
            if (countrySelect.value) {
                window.location.href = `country.html?name=${countrySelect.value}`;
            }
        });

要知道一個概念 getElementById 是拿到 DOM元素(可以自己印出來看看) 要拿到input元素的值 需要使用 .value 去取值

const countrySelect = document.getElementById('selectCountry');
console.log(countrySelect) //試試看會印出甚麼