Object.entries和addEventListener

问题描述 投票:0回答:2

我有这个对象,我想在创建的选项中显示键,并在.info <p>标记中显示值。然后,当我使用addEventListener更改城市时,我想更改信息文本。

我的问题是,是否可以在info中使用for(const [city, info] of entries)中的addEventListener function?我试图将eventListener放在for循环中,但是效果不佳。但是我可以通过某种方式将信息传递给另一个功能吗?还是只是循环键,然后再对addEventListener函数中的值进行循环更好?

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity);

    let currentCity = cityWithInfoPrompt.options[cityWithInfoPrompt.selectedIndex];
    if(currentCity.textContent == city) {
        document.querySelector(".info").textContent = info;
    }
}
<body>
    <select name="cities-with-info" id="cities-with-info"></select>
    <p>Info: <span class="info"></span></p>
    <script src="eventTarget.js"></script>
</body>
javascript
2个回答
1
投票

为带有信息的城市附加事件侦听器

 cityWithInfoPrompt.addEventListener('change',function (event) {
            document.querySelector('.info').innerHTML =  event.target.value
  });

0
投票

您可以将事件附加到循环之外,在此循环中可以在选定值和对象之间匹配值:

let citiesWithInfo = {"New York": 'The biggest city in the world.',
    "Los Angeles": 'Home of the Hollywood sign.',
    "Maui": 'A city on the beautiful island of Hawaii.',
    "Vancover": 'It\'s a city where it rains alot. And I mean alot.',
    "Miami": 'The samba city of the world.'
};

const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);

for(const [city, info] of entries) {
    let optionCity = document.createElement("option");
    optionCity.textContent = city;
    optionCity.value = city;
    cityWithInfoPrompt.appendChild(optionCity); 
}

cityWithInfoPrompt.addEventListener('change', function(){
  let currentCity = this.options[this.selectedIndex].value;
  document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);
<body>
    <select name="cities-with-info" id="cities-with-info"></select>
    <p>Info: <span class="info"></span></p>
    <script src="eventTarget.js"></script>
</body>
© www.soinside.com 2019 - 2024. All rights reserved.