您将如何使用 JavaScript 创建一个取消隐藏/隐藏内容的切换按钮?

我试图隐藏单击按钮时显示的内容。


这是我的起始 HTML:


        <div class="sunrise-section" id="hide-show">

          <h3>SUNRISE</h3>

          <p class="sunrise">5:40 A.M.</p>

        </div>


        <div class="sunset-section" id="hide-show">

          <h3>SUNSET</h3>

          <p class="sunset">8:05 P.M.</p>

        </div>


        <div class="navbar-bottom">

            <button onclick="onClick"><img src="https://image.flaticon.com/icons/svg/892/892499.svg" alt="click for details" height="18px" id="navbar-bottom-button"></button>

        </div>


这是我的起始 JavaScript(onClick 函数是最后一个;我包含了所有内容以显示上下文):


window.addEventListener('load', ()=> {

    let long;

    let lat;

    let locationTimeZone = document.querySelector('.location-timezone');

    let temperatureDegree = document.querySelector('.temperature-degree');

    let humidity = document.querySelector('.humidity');

    let todayDate = document.querySelector('.today-date');

    let windSpeed = document.querySelector('.wind-speed');

    let visibility = document.querySelector('.visibility');

    let pressure = document.querySelector('.pressure');

    let sunrise = document.querySelector('.sunrise');

    let sunset = document.querySelector('.sunset');

    let myDate = new Date();


    if (navigator.geolocation) {

        navigator.geolocation.getCurrentPosition(position => {

            long = position.coords.longitude;

            lat = position.coords.latitude;


            const proxy = 'https://cors-anywhere.herokuapp.com/';

            const api = `${proxy}https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=d5f88bf8e740a9d82677f46f346f0a33&units=Imperial`;

            }

                    

        } )


        });

    }

}); 

我试图将 .getElementById("hide-show") 更改为 document.querySelectorAll('[id=hide-show]') 并且没有任何变化。


我感谢任何可以帮助我更好地理解这个问题的意见!


长风秋雁
浏览 113回答 1
1回答

慕尼黑8549860

我认为如果您将 javascript 放在单独的文件中,则永远不会调用 onClick 函数。这里有一个简单的方法来做到这一点,它被称为事件委托,在一个循环中有一个监听器比多个监听器更好。let elements = document.querySelectorAll('.hide-show');document.addEventListener('click', e => {&nbsp; &nbsp;if (e.target.closest('button')) {&nbsp; &nbsp; &nbsp; elements.forEach(el => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;el.classList.contains('hidden') ? el.classList.remove('hidden') : el.classList.add('hidden');&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp;}}).hidden {&nbsp; display: none}<div class="sunrise-section hide-show" id="one">&nbsp; <h3>SUNRISE</h3>&nbsp; <p class="sunrise">5:40 A.M.</p></div><div class="sunset-section hide-show" id="two">&nbsp; <h3>SUNSET</h3>&nbsp; <p class="sunset">8:05 P.M.</p></div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="navbar-bottom">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button><img src="https://image.flaticon.com/icons/svg/892/892499.svg" alt="click for details" height="18px" id="navbar-bottom-button"></button>&nbsp; &nbsp; &nbsp; &nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript