简体   繁体   English

我需要切换常见问题页面的显示设置。 我制作了一个有效的 js 脚本,但它非常重复,我该如何简化它?

[英]I need to toggle display settings for a FAQ page. I made a working js script but it's super repetitive, how could I simplify this?

so I'm building a FAQ page that I want a clickable div with the question to display the answer.所以我正在构建一个常见问题页面,我想要一个带有问题的可点击 div 来显示答案。 I wrote the following and it works, but it is not optimal in anyway because I have a function for each div.我写了以下内容并且它有效,但无论如何它都不是最佳的,因为我为每个 div 都有一个函数。 How can I simplify and optimize this code?如何简化和优化此代码? I was thinking of using a for loop but got lost in the way.我正在考虑使用 for 循环,但迷路了。

Here's html:这是html:

NOTE 1 : please don't mind the inline styles, I'm planning on moving those to the stylesheet but I was testing independently.注意 1 :请不要介意内联样式,我打算将它们移到样式表中,但我是独立测试的。

NOTE 2: the {% include tags %} are from liquid variables, the backend will render those properly so please ignore those.注意 2: {% include tags %}来自液体变量,后端将正确呈现这些,因此请忽略它们。

 <div id="question-container1" style="padding: 40px 0 20px 0;" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq1()"> <h3 style="text-align: center; color: #115939; padding-top: 60px;">1. ¿Cuándo recibiré mi terrario?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq1" style="display: none; padding: 20px; text-align: center; color: #115939;">Estaremos enviando los terrarios en la primera semana de diciembre.</p> </div> <div id="question-container2" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq2()"> <h3 style="text-align: center; color: #115939;">2. ¿Cómo funciona el envío con plantas?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq2" style="display: none; padding: 20px; text-align: center; color: #115939;">Utilizamos envío de UPS para el día siguiente, esto para que las plantas no pasen tanto tiempo en el traslado. Todos pedidos serán envíados de lunes a miércoles, esto para evitar ante cualquier percance, que las plantas pasen el fin de semana en las instalaciones de la mensajería. El envío no tiene costo.</p> </div> <div id="question-container3" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq3()"> <h3 style="text-align: center; color: #115939;">3. ¿Cómo lo armo?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq3" style="display: none; padding: 20px; text-align: center; color: #115939;">Te recomendamos armar tu terrario tan pronto lo recibas o colocar las plantas en una maceta para utilizarlas más adelante. Recuerda que puedes agregar más plantas ya estando armado el terrario. Sigue las instrucciones incluídas, o visita este <a href="">link.</a></p> </div> <div id="question-container4" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq4()"> <h3 style="text-align: center; color: #115939;">4. ¿Qué tipos de pago aceptan?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq4" style="display: none; padding: 20px; text-align: center; color: #115939;">Aceptamos pagos con tarjeta de crédito, débito, PayPal, pagos en efectivo en Oxxo o transferencia interbancaria SPEI.</p> </div>

And here's javascript这是 javascript

 const despliegueFaq1 = () => { let x = document.getElementById ('esconder_faq1'); if (x.style.display === "none"){ x.style.display = "block"; } else { x.style.display = "none"; } } const despliegueFaq2 = () => { let x = document.getElementById ('esconder_faq2'); if (x.style.display === "none"){ x.style.display = "block"; } else { x.style.display = "none"; } } const despliegueFaq3 = () => { let x = document.getElementById ('esconder_faq3'); if (x.style.display === "none"){ x.style.display = "block"; } else { x.style.display = "none"; } } const despliegueFaq4 = () => { let x = document.getElementById ('esconder_faq4'); if (x.style.display === "none"){ x.style.display = "block"; } else { x.style.display = "none"; } }

On Javascript code, the content of each function is almost the same except the id like esconder_faq1 , esconder_faq2 ...在 Javascript 代码中,除了esconder_faq1esconder_faq2 ... 这样的id外,每个函数的内容几乎相同。

So ids' are composed with esconder_faq prefix and number.所以 ids' 由esconder_faq前缀和数字组成。

So you can make a new function that retrieves that index number as param and use that number to get the id like "esconder_faq" + index as follows.因此,您可以创建一个新函数来检索该索引号作为参数,并使用该number来获取 id,如"esconder_faq" + index ,如下所示。

On html, you can call the function with index number like onclick=despliegueFaq(1) .在 html 上,您可以使用索引号调用函数,例如onclick=despliegueFaq(1)

 const despliegueFaq = (index) => { let x = document.getElementById('esconder_faq' + index); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } }
 <div id="question-container1" style="padding: 40px 0 20px 0;" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq(1)"> <h3 style="text-align: center; color: #115939; padding-top: 60px;">1. ¿Cuándo recibiré mi terrario?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq1" style="display: none; padding: 20px; text-align: center; color: #115939;">Estaremos enviando los terrarios en la primera semana de diciembre.</p> </div> <div id="question-container2" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq(2)"> <h3 style="text-align: center; color: #115939;">2. ¿Cómo funciona el envío con plantas?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq2" style="display: none; padding: 20px; text-align: center; color: #115939;">Utilizamos envío de UPS para el día siguiente, esto para que las plantas no pasen tanto tiempo en el traslado. Todos pedidos serán envíados de lunes a miércoles, esto para evitar ante cualquier percance, que las plantas pasen el fin de semana en las instalaciones de la mensajería. El envío no tiene costo.</p> </div> <div id="question-container3" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq(3)"> <h3 style="text-align: center; color: #115939;">3. ¿Cómo lo armo?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq3" style="display: none; padding: 20px; text-align: center; color: #115939;">Te recomendamos armar tu terrario tan pronto lo recibas o colocar las plantas en una maceta para utilizarlas más adelante. Recuerda que puedes agregar más plantas ya estando armado el terrario. Sigue las instrucciones incluídas, o visita este <a href="">link.</a></p> </div> <div id="question-container4" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq(4)"> <h3 style="text-align: center; color: #115939;">4. ¿Qué tipos de pago aceptan?</h3> <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span> <p id="esconder_faq4" style="display: none; padding: 20px; text-align: center; color: #115939;">Aceptamos pagos con tarjeta de crédito, débito, PayPal, pagos en efectivo en Oxxo o transferencia interbancaria SPEI.</p> </div>

The easy solution here is to use a class to identify all the div s you're interested in taking this action on.这里的简单解决方案是使用一个class来标识您有兴趣采取此操作的所有div Let's say you give each of your div s the class name question :假设您为每个divclassquestion

<div class="question" id="question-container1" style="padding: 40px 0 20px 0;" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq1()">
    <h3 style="text-align: center; color: #115939; padding-top: 60px;">1. ¿Cuándo recibiré mi terrario?</h3>
    <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span>
    <p id="esconder_faq1" style="display: none; padding: 20px; text-align: center; color: #115939;">Estaremos enviando los terrarios en la primera semana de diciembre.</p>
    
</div>

<div class="question" id="question-container2" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq2()">
    <h3 style="text-align: center; color: #115939;">2. ¿Cómo funciona el envío con plantas?</h3>
    <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span>
    <p id="esconder_faq2" style="display: none; padding: 20px; text-align: center; color: #115939;">Utilizamos envío de UPS para el día siguiente, esto para que las plantas no pasen tanto tiempo en el traslado. Todos pedidos serán envíados de lunes a miércoles, esto para evitar ante cualquier percance, que las plantas pasen el fin de semana en las instalaciones de la mensajería. El envío no tiene costo.</p>
</div>

<div class="question" id="question-container3" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq3()">
    <h3 style="text-align: center; color: #115939;">3. ¿Cómo lo armo?</h3>
    <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span>
    <p id="esconder_faq3" style="display: none; padding: 20px; text-align: center; color: #115939;">Te recomendamos armar tu terrario tan pronto lo recibas o colocar las plantas en una maceta para utilizarlas más adelante. Recuerda que puedes agregar más plantas ya estando armado el terrario. Sigue las instrucciones incluídas, o visita este <a href="">link.</a></p>
    
</div>

<div class="question" id="question-container4" style="padding: 40px 0 20px 0; border-top: 1px solid rgba(17,89,57,.3);" class="question-lillipot preguntas-lillipot" onclick="despliegueFaq4()">
    <h3 style="text-align: center; color: #115939;">4. ¿Qué tipos de pago aceptan?</h3>
    <span style=" display: block; text-align: center; margin: 0 auto;">{% include 'icon-chevron-down' %}</span>
    <p id="esconder_faq4" style="display: none; padding: 20px; text-align: center; color: #115939;">Aceptamos pagos con tarjeta de crédito, débito, PayPal, pagos en efectivo en Oxxo o transferencia interbancaria SPEI.</p>
    
</div>

Then all you need to do to refactor this code is the following:然后你需要做的就是重构这个代码如下:

let questions = document.getElementsByClassName("question");

for (var i=0;i<questions.length;i++) {
    var x = questions[i];
    if (x.style.display === "none"){
            x.style.display = "block";
        } else {
            x.style.display = "none";
        }
    };

At this point you could also reevaluate whether you actually need all those separate id values.此时,您还可以重新评估您是否真的需要所有这些单独的id值。 If you don't need to identify them separately it might be worthwhile to just get rid of them for simplicity's sake.如果您不需要单独识别它们,为了简单起见,将它们去掉可能是值得的。

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

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