简体   繁体   English

用通配符合并功能?

[英]Consolidate function with wildcard?

I want to consolidate the following function into something more eloquent. 我想将以下功能整合为更雄辩的功能。

Basically I want to get element by id like "title#" and push "#" into the function so that if you click on title#x you will ReverseDisplay link#xcontent. 基本上,我想通过id(例如“ title#”)获取元素并将“#”按入函数,以便如果单击title#x,则将ReverseDisplay link#xcontent。

Appreciate any advice thank you. 感谢任何建议,谢谢。

 document.getElementById("title1").onclick = function() {myFunction()}; function myFunction() { ReverseDisplay('link1content'); } document.getElementById("title2").onclick = function() {myFunction1()}; function myFunction1() { ReverseDisplay('link2content'); } document.getElementById("title3").onclick = function() {myFunction2()}; function myFunction2() { ReverseDisplay('link3content'); } document.getElementById("title4").onclick = function() {myFunction3()}; function myFunction3() { ReverseDisplay('link4content'); } document.getElementById("title5").onclick = function() {myFunction4()}; function myFunction4() { ReverseDisplay('link5content'); } document.getElementById("title6").onclick = function() {myFunction5()}; function myFunction5() { ReverseDisplay('link6content'); } document.getElementById("title7").onclick = function() {myFunction6()}; function myFunction6() { ReverseDisplay('link7content'); } document.getElementById("title8").onclick = function() {myFunction7()}; function myFunction7() { ReverseDisplay('link8content'); } 

You can use document.querySelectorAll() : 您可以使用document.querySelectorAll()

 const ReverseDisplay = x => console.log(x) Array.from(document.querySelectorAll('[id^="title"]')) .forEach(el => el.addEventListener('click', () => ReverseDisplay(`link${el.id.split('title').join('')}content`))) 
 <div id="title1">title1</div> <div id="title2">title2</div> <div id="title3">title3</div> 

document.querySelectorAll() returns a NodeList , so we have to use Array.from() to be able to use array methods like forEach . document.querySelectorAll()返回一个NodeList ,因此我们必须使用Array.from()才能使用诸如forEach类的数组方法。 Then we add a click event listener to each element using addEventListener() (see addEventListener vs onclick ). 然后,我们使用addEventListener()将click事件侦听器添加到每个元素(请参见addEventListener与onclick )。 Using split('title').join('') we remove the 'title' part from the ID and leave only the number. 使用split('title').join('')我们从ID中删除了'title'部分,仅保留了数字。 If you're wondering what are these ` and => , see template literals and arrow functions . 如果您想知道这些`=>是什么,请参阅模板文字箭头函数

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

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