简体   繁体   English

使用 HTML 按钮和 Javascript 切换显示/隐藏包含在 Span class 标签中的 html 文本

[英]Toggle show/hide html text wrapped in Span class tags using HTML button and Javascript

I have a decent command of HTML and CSS but a complete newbie when it comes to Javascript.我对 HTML 和 CSS 有很好的掌握,但对 Javascript 完全是个新手。

I have a simple HTML page that I would like to include a button on, to toggle the display of text already wrapped in a span class eg我有一个简单的 HTML 页面,我想在上面包含一个按钮,以切换已经包含在跨度 class 中的文本的显示,例如

<span class="xxx">TEXT</span>

There are two separate span classes I'm using and ideally, I'd like the click of one button to show/hide both.我正在使用两个单独的跨度类,理想情况下,我希望单击一个按钮来显示/隐藏两者。

Right now I'm using CSS to hide them using the property "Display: none".现在我正在使用 CSS 来使用属性“显示:无”隐藏它们。

Can you show me how to achieve this?你能告诉我如何实现这一目标吗? Hope this clear, thank you.希望这个清楚,谢谢。

Using Vanilla Javascript on ES5 syntax:在 ES5 语法上使用 Vanilla Javascript:

function toggleSpanElements() {
 var span1 = document.querySelector('#span1');
 var span2 = document.querySelector('#span2');
 span1.style.display = span1.style.display === 'none' ? 'block' : 'none';
 span2.style.display = span2.style.display === 'none' ? 'block' : 'none';
}

Just attach that function to your button in the following way:只需按以下方式将 function 附加到您的按钮即可:

    <button onclick="toggleSpanElements()">Toggle!</button>

This should work (ES6):这应该有效(ES6):

 let btn = document.getElementById('btn'); let toggle = document.querySelectorAll('.toggle'); btn.onclick = () => { for(let x of toggle) { x.classList.toggle('hide'); } };
 .toggle.hide { display: none; }
 <button id="btn">Toggle</button> <p>Name: <span class="toggle name">John</span></p> <p>Age: <span class="toggle age">20</span></p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM