简体   繁体   English

如何使用 Vanilla JS 切换多个 html 文本元素?

[英]How to toggle multiple html text elements using Vanilla JS?

I am trying to use the most efficient method of toggling the innerHTML on multiple elements.我正在尝试使用最有效的方法在多个元素上切换 innerHTML。 I am still learning and have gotten stuck at this point我仍在学习并且在这一点上陷入困境

 var button = document.querySelectorAll(".title"); for (i=0; i < button.length; i++) { button[i].addEventListener('click', textToggle) } function textToggle() { if (button.getAttribute("data-text-swap") == button.innerHTML) { button.innerHTML = button.getAttribute("data-text-original"); } else { button.setAttribute("data-text-original", button.innerHTML); button.innerHTML = button.getAttribute("data-text-swap"); } }
 <details> <summary class="title" data-text-swap="Hide text"> Show text </summary> <p>text</p> </details> <details> <summary class="title" data-text-swap="Hide text"> Show text </summary> <p>text</p> </details>

You are almost there.你快到了。 You just need to operate on the e.target element, which is the element associated with the click event, and not the button variable which is a list of elements.您只需要对e.target元素进行操作,它是与click事件关联的元素,而不是作为元素列表的button变量。

 var button = document.querySelectorAll(".title"); for (i=0; i < button.length; i++) { button[i].addEventListener('click', textToggle) } function textToggle(e) { const el = e.target; if (el.getAttribute("data-text-swap") == el.innerHTML) { el.innerHTML = el.getAttribute("data-text-original"); } else { el.setAttribute("data-text-original", el.innerHTML); el.innerHTML = el.getAttribute("data-text-swap"); } }
 <details> <summary class="title" data-text-swap="Hide text"> Show text </summary> <p>text</p> </details> <details> <summary class="title" data-text-swap="Hide text"> Show text </summary> <p>text</p> </details>

You refer to button that is not an element but an array.您指的button不是元素而是数组。 You can refer to the clicked button in the callbackwith the keyword this可以通过关键字this引用回调中点击的按钮

 var button = document.querySelectorAll(".title"); for (i=0; i < button.length; i++) { button[i].addEventListener('click', textToggle) } function textToggle() { if (this.getAttribute("data-text-swap") == this.innerHTML) { this.innerHTML = this.getAttribute("data-text-original"); } else { this.setAttribute("data-text-original", this.innerHTML); this.innerHTML = this.getAttribute("data-text-swap"); } }
 <details> <summary class="title" data-text-swap="Hide text"> Show text </summary> <p>text</p> </details> <details> <summary class="title" data-text-swap="Hide text"> Show text </summary> <p>text</p> </details>

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

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