繁体   English   中英

在按钮单击 + 更改按钮文本时触发 DIV 内容

[英]Trigger DIV content on button click + change button text

我正在尝试通过按钮触发 DIV 的可见性。

我的代码如下所示:

 function myFunction() { var moreText = document.getElementById("csrmore"); var x = document.getElementById("myDIV"); let ishidden = x.classList.contains("hidden") if (ishidden == true) { x.classList.remove("hidden"); x.classList.add("shown"); moreText.innerHTML = "Show less"; } else { x.classList.remove("shown"); x.classList.add("hidden"); moreText.innerHTML = "Show more"; } }
 div { width: 100px; height: 100px; }.hidden { display:none }.shown { display:block; }
 <button id="csrmore" onclick="myFunction()"> Show more </button> <div id="myDIV" class="hidden"> This is the triggerable content. </div>

小提琴: https://jsfiddle.net/6zxa0Lg2/

它工作正常,但是由于我是 JS 初学者,我想知道这是否是不好的做法,还是一段完全好的代码?

感谢您的每一个帮助:)

这是 go 关于它的另一种方法。 让一切都是相对的。 单击该按钮,javascript 会找到与该按钮关联的内容以显示/隐藏。 这样您就不需要任何 ID 标签,并且您可以在页面上拥有任意数量的显示/隐藏按钮。

 document.addEventListener('DOMContentLoaded', () => { // after the page loads... document.querySelectorAll('.csrmore').forEach(button => { // find all the 'show more' buttons and for each one... button.addEventListener('click', e => { // when someone clicks this button let content = e.target.closest('.container').querySelector('.content'); // find the content div associated with this button content.classList.toggle('hidden'); // toggle on or off the content e.target.innerText = content.classList.contains('hidden')? 'Show more': 'Hide'; // change the text of the button }) }) })
 div { width: 100px; height: 100px; }.hidden { display: none }
 <div class='container'> <button class="csrmore"> Show more </button> <div class="content hidden"> This is the triggerable content. </div> </div> <hr> <div class='container'> <button class="csrmore"> Show more </button> <div class="content hidden"> This is the triggerable content. </div> </div>

这是一个很好的方法,这不是我不会想出的解决方案。 但它实际上非常聪明。 我本以为可以通过在单击按钮时将 TARGET.style.visibility 切换为“隐藏”或“可见”来完成它,但同样,您的代码看起来非常好!

暂无
暂无

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

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