简体   繁体   English

在所选元素 ID 上切换 javascript

[英]Switch javascript on element ID selected

how to simplify the javascript code not to repeat the functions as many times as an id element is present?如何简化 javascript 代码不重复功能与 id 元素一样多次? I also found it difficult to add the CSS selector #selected on Balide li clicked.我还发现很难添加 CSS 选择器#selected on Balide li 点击。

 function LightBlue() { document.getElementsByTagName('body')[0].setAttribute("id", "LightBlue"); document.getElementsByTagName('body')[0].style.color = 'Black'; } function MorningSalad() { document.getElementsByTagName('body')[0].setAttribute("id", "MorningSalad"); document.getElementsByTagName('body')[0].style.color = 'Black'; } function AngelCare() { document.getElementsByTagName('body')[0].setAttribute("id", "AngelCare"); document.getElementsByTagName('body')[0].style.color = 'Black'; } function GrassShampoo() { document.getElementsByTagName('body')[0].setAttribute("id", "GrassShampoo"); document.getElementsByTagName('body')[0].style.color = 'Black'; } etc... document.getElementById('LightBlue').onclick = LightBlue; document.getElementById('MorningSalad').onclick = MorningSalad; document.getElementById('AngelCare').onclick = AngelCare; document.getElementById('GrassShampoo').onclick = GrassShampoo; etc...
 body{margin:3em;padding:0;font-family:sans-serif;font-size:18px;line-height:1.5;height:1500px;margin-top:50px} h1{line-height:1.25;margin:2em 0 0} p{margin:.5em 0} li:hover{cursor:pointer} #switcher{list-style:none;margin:0;padding:0;overflow:hidden} #switcher li{float:left;width:30px;height:30px;margin:0 15px 15px 0;border-radius:30px;border:3px solid #000}.selected{opacity:.2} #LightBlue{background:linear-gradient(-225deg,#9EFBD3 0%,#57E9F2 48%,#45D4FB 100%)} #MorningSalad{background:linear-gradient(-225deg,#B7F8DB 0%,#50A7C2 100%)} #AngelCare{background:linear-gradient(-225deg,#FFE29F 0%,#FFA99F 48%,#FF719A 100%)} #GrassShampoo{background:linear-gradient(-225deg,#DFFFCD 0%,#90F9C4 48%,#39F3BB 100%)} #SeaLord{background:linear-gradient(-225deg,#2CD8D5 0%,#C5C1FF 56%,#FFBAC3 100%)} #SunVeggie{background:linear-gradient(-225deg,#20E2D7 0%,#F9FEA5 100%)} #RoyalGarden{background-image:linear-gradient(to right,#ed6ea0 0%,#ec8c69 100%)} #HighFlight{background:linear-gradient(to right,#0acffe 0%,#495aff 100%)} #AfricanField{background:linear-gradient(-45deg,#FFC796 0%,#FF6B95 100%)} #HappyUnicorn{background:linear-gradient(to top,#b3ffab 0%,#12fff7 100%)} #ColorfulPeach{background:linear-gradient(to right,#ed6ea0 0%,#ec8c69 100%)} #YoungGrass{background:linear-gradient(to top,#9be15d 0%,#00e3ae 100%)} #Seashore{background-image:linear-gradient(to top,#209cff 0%,#68e0cf 100%)} #FlyingLemon{background:linear-gradient(60deg,#64b3f4 0%,#c2e59c 100%)} #HealthyWater{background:linear-gradient(60deg,#96deda 0%,#50c9c3 100%)} #PassionateBed{background:linear-gradient(to right,#ff758c 0%,#ff7eb3 100%)} #SummerGames{background:linear-gradient(to right,#92fe9d 0%,#00c9ff 100%)} #ShadyWater{background:linear-gradient(to right,#74ebd5 0%,#9face6 100%)} #FlyHigh{background:linear-gradient(to top,#48c6ef 0%,#6f86d6 100%)} #StrongBliss{background:linear-gradient(to right,#f78ca0 0%,#f9748f 19%,#fd868c 60%,#fe9a8b 100%)} #HappyAcid{background:linear-gradient(to top,#37ecba 0%,#72afd3 100%)} #ItmeoBranding{background:linear-gradient(180deg,#2af598 0%,#009efd 100%)} #LemonGate{background:linear-gradient(to top,#96fbc4 0%,#f9f586 100%)} #SharpeyeEagle{background:linear-gradient(to top,#9890e3 0%,#b1f4cf 100%)} #Blessing{background:linear-gradient(to top,#fddb92 0%,#d1fdff 100%)} #HappyFisher{background:linear-gradient(120deg,#89f7fe 0%,#66a6ff 100%)} #AriellesSmile{background:radial-gradient(circle 248px at center,#16d9e3 0%,#30c7ec 47%,#46aef7 100%)} #NearMoon{background:linear-gradient(to top,#5ee7df 0%,#b490ca 100%)} #TrueSunset{background:linear-gradient(to right,#fa709a 0%,#fee140 100%)} #NewLife{background:linear-gradient(to right,#43e97b 0%,#38f9d7 100%)} #MalibuBeach{background:linear-gradient(to right,#4facfe 0%,#00f2fe 100%)} #DeepBlue{background:linear-gradient(120deg,#e0c3fc 0%,#8ec5fc 100%)} #WinterNeva{background:linear-gradient(120deg,#a1c4fd 0%,#c2e9fb 100%)} #SunnyMorning{background:linear-gradient(120deg,#f6d365 0%,#fda085 100%)} #TemptingAzure{background:linear-gradient(120deg,#84fab0 0%,#8fd3f4 100%)}
 <ul id="switcher"> <li id="LightBlue"></li> <li id="MorningSalad"></li> <li id="AngelCare"></li> <li id="GrassShampoo"></li> <li id="SeaLord"></li> <li id="SunVeggie"></li> <li id="RoyalGarden"></li> <li id="HighFlight"></li> <li id="AfricanField"></li> <li id="HappyUnicorn"></li> <li id="ColorfulPeach"></li> <li id="YoungGrass"></li> <li id="Seashore"></li> <li id="FlyingLemon"></li> <li id="HealthyWater"></li> <li id="PassionateBed"></li> <li id="SummerGames"></li> <li id="ShadyWater"></li> <li id="FlyHigh"></li> <li id="StrongBliss"></li> <li id="HappyAcid"></li> <li id="ItmeoBranding"></li> <li id="LemonGate"></li> <li id="SharpeyeEagle"></li> <li id="Blessing"></li> <li id="HappyFisher"></li> <li id="AriellesSmile"></li> <li id="NearMoon"></li> <li id="TrueSunset"></li> <li id="NewLife"></li> <li id="MalibuBeach"></li> <li id="DeepBlue"></li> <li id="WinterNeva"></li> <li id="SunnyMorning"></li> <li id="TemptingAzure"></li> </ul> <h1>What's your favorite color?</h1> <p>Try clicking on one of the above colors to change the colors on this page!</p>

You could use the buttons themselves to hold the value to change to, then assign one function to listen for clicks on all of them:您可以使用按钮本身来保存要更改的值,然后分配一个 function 来监听所有按钮的点击:

e: Or use class swapping, per good suggestion. e: 或者使用 class 交换,每个好建议。 Excercise left to reader to not clear out any important classnames.留给读者的练习不要清除任何重要的类名。

 let changers = document.querySelectorAll('.changer'); changers.forEach(element => { element.addEventListener('click', (e)=>{ // document.body.style.backgroundColor = e.target.getAttribute('data-color'); // or as css class document.body.className=""; document.body.classList.add( e.target.getAttribute('data-colourclass') ) }) });
 .LightBlue{background:linear-gradient(-225deg,#9EFBD3 0%,#57E9F2 48%,#45D4FB 100%)}.MorningSalad{background:linear-gradient(-225deg,#B7F8DB 0%,#50A7C2 100%)}.AngelCare{background:linear-gradient(-225deg,#FFE29F 0%,#FFA99F 48%,#FF719A 100%)}
 <li class='changer' data-colourclass="LightBlue">LightBlue</li> <li class='changer' data-colourclass="AngelCare">AngelCare</li> <li class='changer' data-colourclass="MorningSalad" >MorningSalad</li>

I like the answer by Gavin, but thought you might also be interested in this:我喜欢 Gavin 的回答,但认为您可能也对此感兴趣:

If you have a few functions that you want to be able to call by their string-name, you should just use an object like this:如果您有几个函数希望能够通过它们的字符串名称调用,您应该只使用 object,如下所示:

function a() {}

function b() {}

const funcList = {
  'a': a,
  'b': b
}


// then call the function by string name:
funcList['a']();
funcList['b']();

You can also define the function directly inside the object if that's preferred:如果愿意,您还可以直接在 object 中定义 function :

const funcList = {
  'a': function() {},
  'b': function() {}
}

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

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