Soy un novato jQuery. Tengo la funcionalidad que quiero, pero estoy seguro de que mi código jQuery podría simplificarse mucho: hay mucha repetición.

Por ejemplo, cada clic produce casi el mismo resultado exacto: ocultar 7 divs y mostrar 1. Supongo que hay una manera de alternar todos los divs a la vez.

Indíqueme en la dirección correcta sobre cómo simplificar jQuery.

Gracias. La versión en línea de la página está aquí.

body {background-image: url(images/bg-page.jpg); background-size: cover; repeat: no-repeat;}
#selector {list-style: none; max-width: 1322px; margin: 0 auto; padding-left: 0; -webkit-padding-start: 0; margin-bottom: 0;}
#selector li {display: inline-block; width: 11.625%; margin-right: 0.75%; margin-top: 1%; background-color: #012F60; height: 70px; display: inline-table; vertical-align: top}
#selector li:last-child {margin-right: 0%}
#selector li#job.active {background-color: #93CB32;}
#selector li#help.active {background-color: #EC832A;}
#selector li#ndis.active {background-color: blue;}
#selector li#training.active {background-color: purple;}
#selector li#injured.active {background-color: orange;}
#selector li#refer.active {background-color: yellow;}
#selector li#psych.active {background-color: aqua;}
#selector li#employer.active {background-color: black;}
#selector li a {color: white; text-align: center; vertical-align: middle; display: table-cell; text-decoration: none;}
#selection {max-width: 1322px; margin: 0 auto; margin-top: 0;}
#selection div {padding: 1em 0;}
#selection h2 {margin-top: 0;}
#div-job, #div-help, #div-ndis, #div-training, #div-injured, #div-refer, #div-psych, #div-employer {display: none; text-align: center; color: white;}
#div-job {background-color: #93CB32;}
#div-help {background-color: #EC832A;}
#div-ndis {background-color: blue;}
#div-training {background-color: purple;}
#div-injured {background-color: orange;}
#div-refer {background-color: yellow;}
#div-psych {background-color: aqua;}
#div-employer {background-color: black;}
<div id="page">

    <ul id="selector">
        <li id="job" class="active"><a href="#">I want to find a job</a></li>
        <li id="help"><a href="#">I need help at work</a></li>
        <li id="ndis"><a href="#">NDIS</a></li>
        <li id="training"><a href="#">I need training</a></li>
        <li id="injured"><a href="#">I've been injured at work</a></li>
        <li id="refer"><a href="#">I want to refer</a></li>
        <li id="psych"><a href="#">Psych service</a></li>
        <li id="employer"><a href="#">I'm an employer</a></li>
    </ul>
    <div id="selection">
        <div id="div-job">
            <h2>Looking for a job?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>DES for individuals</option>
                <option>DES for youth</option>
                <option>NDIS - individual employment support</option>
                <option>NDIS - youth</option>
                <option>PHaMs</option>
                <option>DES for employers (recruitment)</option>
            </select>
        </div>
        <div id="div-help">
            <h2>Looking for help?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>NDIS - youth</option>
                <option>Psych services - EAP - for individual</option>
                <option>Psych services for H@W - individual</option>
                <option>Psych services for H@W - corporate</option>
                <option>Allied Health Physical services for H@W</option>
                <option>Allied Health Physical services for individuals</option>
                <option>WR for individuals</option>
                <option>Psych services - Workplace rehab - Individual</option>
                <option>NPA</option>
            </select>
        </div>
        <div id="div-ndis">
            <h2>National Disability Insurance Scheme (NDIS)?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>DES for employers (recruitment)</option>
                <option>NDIS - Allied health services </option>
                <option>NDIS - individual employment support</option>
                <option>PHaMs</option>
                <option>NDIS - youth</option>
                <option>Psych services for NDIS</option>
                <option>Allied Health Physical services for NDIS</option>
            </select>
        </div>    
        <div id="div-training">
            <h2>Need training?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>NDIS - individual employment support</option>
                <option>NDIS - youth</option>
                <option>Training - MHFA - for individuals</option>
                <option>Training - Accredited (RTO) - for individuals</option>
            </select>
        </div>
        <div id="div-injured">
            <h2>Been injured at work?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>Allied Health Physical services for individuals</option>
                <option>WR for individuals</option>
                <option>Psych services - Workplace rehab - Individual</option>
            </select>
        </div>
        <div id="div-refer">
            <h2>Want to make a referral?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>Diversity and inclusion for employers</option>
                <option>DES for individuals</option>
                <option>DES for community services</option>
                <option>DES for youth</option>
                <option>H@W for employers</option>
                <option>H@W for GP/Medical</option>
                <option>H@W for individuals</option>
                <option>NDIS - Allied health services</option>
                <option>NDIS - individual employment support</option>
                <option>NDIS - Community Services</option>
                <option>NDIS - youth</option>
                <option>Judgment Index (as a reseller) - for employers</option>
                <option>Psych Servcies - HR Consulting</option>
                <option>Psych services - Mediation / conflict management - for employers</option>
                <option>Psych services for NDIS</option>
                <option>Psych services - Counselling / Assessments (e.g. Medicare, WAPHA) - for GP/Medical</option>
                <option>Training - customised (e.g. OHS, wellness, psych, disability awareness) - for employers</option>
                <option>Training - MHFA - for employers</option>
                <option>Training - Accredited (RTO) - for employers</option>
                <option>Allied Health Physical services for employers</option>
                <option>WR for employers</option>
                <option>Allied Health Physical services for insurers</option>
                <option>WR for Insurers</option>
                <option>Allied Health Physical services for GP/Medical</option>
                <option>WR for GPs/Medical</option>
                <option>Allied Health Physical services for H@W</option>
                <option>Allied Health Physical services for NDIS</option>
                <option>Psych services - Workplace rehab - Employer</option>
                <option>Psych services - Workplace rehab - Insurer</option>
                <option>Psych services - Workplace rehab - GP/Medical</option>
            </select>
        </div>
        <div id="div-psych">
            <h2>I need psychological services?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>NDIS - individual employment support</option>
                <option>NDIS - youth</option>
                <option>Judgment Index (as a reseller) - for employers</option>
                <option>Psych Servcies - HR Consulting</option>
                <option>Psych services - EAP - for employer</option>
                <option>Psych services - Mediation / conflict management - for employers</option>
                <option>Psych services - Counselling  / Assessments (e.g. Medicare, WAPHA) - for individual</option>
                <option>Psych services - EAP - for individual</option>
                <option>Psych services for NDIS</option>
                <option>Psych services - Counselling / Assessments (e.g. Medicare, WAPHA) - for GP/Medical</option>
            </select>
        </div>
        <div id="div-employer">
            <h2>Are you an employer?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>Diversity and inclusion for employers</option>
                <option>DES for employers (recruitment)</option>
                <option>H@W for employers</option>
                <option>Judgment Index (as a reseller) - for employers</option>
                <option>Psych Servcies - HR Consulting</option>
                <option>Psych services - EAP - for employer</option>
                <option>Psych services - Mediation / conflict management - for employers</option>
                <option>Training - customised (e.g. OHS, wellness, psych, disability awareness) - for employers</option>
                <option>Training - MHFA - for employers</option>
                <option>Training - Accredited (RTO) - for employers</option>
                <option>Allied Health Physical services for employers</option>
                <option>WR for employers</option>
            </select>
        </div>
    </div>

</div>
$(document).ready(function(){
    $("#job a").click(function(){
        $("#div-job").show();
        $("#div-help").hide();
        $("#div-ndis").hide();
        $("#div-training").hide();
        $("#div-injured").hide();
        $("#div-refer").hide();
        $("#div-psych").hide();
        $("#div-employer").hide();
        $("li#job").addClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").removeClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").removeClass("active");
    });
    $("#help").click(function(){
        $("#div-job").hide();
        $("#div-help").show();
        $("#div-ndis").hide();
        $("#div-training").hide();
        $("#div-injured").hide();
        $("#div-refer").hide();
        $("#div-psych").hide();
        $("#div-employer").hide();
        $("li#job").removeClass("active");
        $("li#help").addClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").removeClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").removeClass("active");
    });
    $("#ndis").click(function(){
        $("#div-job").hide();
        $("#div-help").hide();
        $("#div-ndis").show();
        $("#div-training").hide();
        $("#div-injured").hide();
        $("#div-refer").hide();
        $("#div-psych").hide();
        $("#div-employer").hide();
        $("li#job").removeClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").addClass("active");
        $("li#training").removeClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").removeClass("active");
    });
    $("#training").click(function(){
        $("#div-job").hide();
        $("#div-help").hide();
        $("#div-ndis").hide();
        $("#div-training").show();
        $("#div-injured").hide();
        $("#div-refer").hide();
        $("#div-psych").hide();
        $("#div-employer").hide();
        $("li#job").removeClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").addClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").removeClass("active");
    });
    $("#injured").click(function(){
        $("#div-job").hide();
        $("#div-help").hide();
        $("#div-ndis").hide();
        $("#div-training").hide();
        $("#div-injured").show();
        $("#div-refer").hide();
        $("#div-psych").hide();
        $("#div-employer").hide();
        $("li#job").removeClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").removeClass("active");
        $("li#injured").addClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").removeClass("active");         
    });
    $("#refer").click(function(){
        $("#div-job").hide();
        $("#div-help").hide();
        $("#div-ndis").hide();
        $("#div-training").hide();
        $("#div-injured").hide();
        $("#div-refer").show();
        $("#div-psych").hide();
        $("#div-employer").hide();
        $("li#job").removeClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").removeClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").addClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").removeClass("active"); 
    });
    $("#psych").click(function(){
        $("#div-job").hide();
        $("#div-help").hide();
        $("#div-ndis").hide();
        $("#div-training").hide();
        $("#div-injured").hide();
        $("#div-refer").hide();
        $("#div-psych").show();
        $("#div-employer").hide();
        $("li#job").removeClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").removeClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").addClass("active");
        $("li#employer").removeClass("active");
    });
    $("#employer").click(function(){
        $("#div-job").hide();
        $("#div-help").hide();
        $("#div-ndis").hide();
        $("#div-training").hide();
        $("#div-injured").hide();
        $("#div-refer").hide();
        $("#div-psych").hide();
        $("#div-employer").show();
        $("li#job").removeClass("active");
        $("li#help").removeClass("active");
        $("li#ndis").removeClass("active");
        $("li#training").removeClass("active");
        $("li#injured").removeClass("active");
        $("li#refer").removeClass("active");
        $("li#psych").removeClass("active");
        $("li#employer").addClass("active");
    });
});
2
Steve 5 mar. 2018 a las 10:26

4 respuestas

La mejor respuesta

Puede seleccionar múltiplos, así que esto:

$("#div-help").hide();
$("#div-ndis").hide();

Se convierte

$("#div-help, #div-ndis").hide();

Enjuague y repita con los demás y se simplificará mucho

También debe hacer funciones separadas para mostrar / ocultar, etc., que se repiten, por lo que en lugar de llamar a muchos selectores, llame a las funciones

Entonces de esto:

$("#div-job").hide();
$("#div-help").hide();
$("#div-ndis").hide();

Nosotras vamos a:

$("#div-job, #div-help, #div-ndis").hide();

Y envolverlo en su propia función:

function hideDivs() {
    $("#div-job, #div-help, #div-ndis").hide();
}

Entonces, cuando se requiere que estos estén ocultos, simplemente llame:

hideDivs();

Hay mucho más que puedes hacer, pero este es un comienzo

1
Darren Sweeney 5 mar. 2018 a las 07:30

Recomendaría usar data- atributos y selectores en ellos. Las ID y las clases se guardan mejor para el uso de CSS.

Esto se convierte en:

<!-- Your selectors -->
<li data-selector="job" id="job" class="active">...</li>
...

<!-- Your selection -->
<div data-selection="job" id="div-job">...</div>
...

Luego en el lado del script:

$('[data-selector]').on('click', function() {
  // Hide all selections
  $('[data-selector'].removeClass('active');
  $('[data-selection'].hide();

  // Show only the requested one
  $(this).addClass('active');
  $('[data-selection=' + $(this).data('selector') + ']').show();
});
1
Jeto 5 mar. 2018 a las 08:27

Entonces podrías dar a todos esos elementos div y li una clase común como

 <div id="div-training" class="div-class">
 <li id="job" class="active li-class"><a href="#">I want to find a job</a></li>

Esto reduciría todo el jquery a

$('.li-class').each(function() {
    // for each li add an onclick
    $(this).click(function() {
        // hide all divs
        $('.div-class').each(function() {
            $(this).hide()
        })
        // get current div assuming its named div-[id of clicked li]
        var current = $(this).attr("id");
        var div_id = "#div-" + current;
        // reshow correct div
        $(div_id).show();

        $('.li-class').each(function() {
            // If not the clicked one add active
            if ($(this).attr("id") != current) {
                $(this).removeClass("active");
            } else {
                $(this).addClass("active");
            }
        })
    });
})

Esto no se ha probado, por lo que podría haber algunos errores para resolver. Sin embargo, debería darte una buena idea. También puede agregar un atributo html que apunte al otro div para evitar tener que crear el nombre en javascript

0
hwhite4 5 mar. 2018 a las 07:53

Puede usar algunos selectores genéricos, porque está usando id y debe ser único. Mira mi código a continuación.

$('#selector li').on('click', function(){
  var current = "#div-" + $(this).prop('id');
  $("#selector li").removeClass("active");
  $("#selection > div").hide();
  $(this).addClass("active");
  $(current).show();
});

En el código anterior, Primero estoy haciendo que el evento click sea común usando $('#selector li').on('click', function(){ en lugar de cada clic. Luego de la estructura de su HTML, li y el equivalente div tienen el mismo nombre, excepto la palabra div-. Así que he creado una variable y obtengo el id del elemento en el que se hizo clic y lo agregué con el div- para dirigir el div actual a show.

Ahora estoy reduciendo el código repetido removeClass/hide usando $("#selector li").removeClass("active"); y $("#selection > div").hide();. El símbolo > apuntará a los hijos directos de element en particular. En nuestro caso, todos los div son los hijos directos de #selection. Finalmente, estoy mostrando el div actual y agregando la clase active para el elemento actual.

$('#selector li').on('click', function(){
   var current = "#div-" + $(this).prop('id');
   $("#selector li").removeClass("active");
   $("#selection > div").hide();
   $(this).addClass("active");
   $(current).show();
})
body {background-image: url(images/bg-page.jpg); background-size: cover; repeat: no-repeat;}
#selector {list-style: none; max-width: 1322px; margin: 0 auto; padding-left: 0; -webkit-padding-start: 0; margin-bottom: 0;}
#selector li {display: inline-block; width: 11.625%; margin-right: 0.75%; margin-top: 1%; background-color: #012F60; height: 70px; display: inline-table; vertical-align: top}
#selector li:last-child {margin-right: 0%}
#selector li#job.active {background-color: #93CB32;}
#selector li#help.active {background-color: #EC832A;}
#selector li#ndis.active {background-color: blue;}
#selector li#training.active {background-color: purple;}
#selector li#injured.active {background-color: orange;}
#selector li#refer.active {background-color: yellow;}
#selector li#psych.active {background-color: aqua;}
#selector li#employer.active {background-color: black;}
#selector li a {color: white; text-align: center; vertical-align: middle; display: table-cell; text-decoration: none;}
#selection {max-width: 1322px; margin: 0 auto; margin-top: 0;}
#selection div {padding: 1em 0;}
#selection h2 {margin-top: 0;}
#div-job, #div-help, #div-ndis, #div-training, #div-injured, #div-refer, #div-psych, #div-employer {display: none; text-align: center; color: white;}
#div-job {background-color: #93CB32;}
#div-help {background-color: #EC832A;}
#div-ndis {background-color: blue;}
#div-training {background-color: purple;}
#div-injured {background-color: orange;}
#div-refer {background-color: yellow;}
#div-psych {background-color: aqua;}
#div-employer {background-color: black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page">

    <ul id="selector">
        <li id="job" class="active"><a href="#">I want to find a job</a></li>
        <li id="help"><a href="#">I need help at work</a></li>
        <li id="ndis"><a href="#">NDIS</a></li>
        <li id="training"><a href="#">I need training</a></li>
        <li id="injured"><a href="#">I've been injured at work</a></li>
        <li id="refer"><a href="#">I want to refer</a></li>
        <li id="psych"><a href="#">Psych service</a></li>
        <li id="employer"><a href="#">I'm an employer</a></li>
    </ul>
    <div id="selection">
        <div id="div-job">
            <h2>Looking for a job?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>DES for individuals</option>
                <option>DES for youth</option>
                <option>NDIS - individual employment support</option>
                <option>NDIS - youth</option>
                <option>PHaMs</option>
                <option>DES for employers (recruitment)</option>
            </select>
        </div>
        <div id="div-help">
            <h2>Looking for help?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>NDIS - youth</option>
                <option>Psych services - EAP - for individual</option>
                <option>Psych services for H@W - individual</option>
                <option>Psych services for H@W - corporate</option>
                <option>Allied Health Physical services for H@W</option>
                <option>Allied Health Physical services for individuals</option>
                <option>WR for individuals</option>
                <option>Psych services - Workplace rehab - Individual</option>
                <option>NPA</option>
            </select>
        </div>
        <div id="div-ndis">
            <h2>National Disability Insurance Scheme (NDIS)?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>DES for employers (recruitment)</option>
                <option>NDIS - Allied health services </option>
                <option>NDIS - individual employment support</option>
                <option>PHaMs</option>
                <option>NDIS - youth</option>
                <option>Psych services for NDIS</option>
                <option>Allied Health Physical services for NDIS</option>
            </select>
        </div>    
        <div id="div-training">
            <h2>Need training?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>NDIS - individual employment support</option>
                <option>NDIS - youth</option>
                <option>Training - MHFA - for individuals</option>
                <option>Training - Accredited (RTO) - for individuals</option>
            </select>
        </div>
        <div id="div-injured">
            <h2>Been injured at work?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>Allied Health Physical services for individuals</option>
                <option>WR for individuals</option>
                <option>Psych services - Workplace rehab - Individual</option>
            </select>
        </div>
        <div id="div-refer">
            <h2>Want to make a referral?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>Diversity and inclusion for employers</option>
                <option>DES for individuals</option>
                <option>DES for community services</option>
                <option>DES for youth</option>
                <option>H@W for employers</option>
                <option>H@W for GP/Medical</option>
                <option>H@W for individuals</option>
                <option>NDIS - Allied health services</option>
                <option>NDIS - individual employment support</option>
                <option>NDIS - Community Services</option>
                <option>NDIS - youth</option>
                <option>Judgment Index (as a reseller) - for employers</option>
                <option>Psych Servcies - HR Consulting</option>
                <option>Psych services - Mediation / conflict management - for employers</option>
                <option>Psych services for NDIS</option>
                <option>Psych services - Counselling / Assessments (e.g. Medicare, WAPHA) - for GP/Medical</option>
                <option>Training - customised (e.g. OHS, wellness, psych, disability awareness) - for employers</option>
                <option>Training - MHFA - for employers</option>
                <option>Training - Accredited (RTO) - for employers</option>
                <option>Allied Health Physical services for employers</option>
                <option>WR for employers</option>
                <option>Allied Health Physical services for insurers</option>
                <option>WR for Insurers</option>
                <option>Allied Health Physical services for GP/Medical</option>
                <option>WR for GPs/Medical</option>
                <option>Allied Health Physical services for H@W</option>
                <option>Allied Health Physical services for NDIS</option>
                <option>Psych services - Workplace rehab - Employer</option>
                <option>Psych services - Workplace rehab - Insurer</option>
                <option>Psych services - Workplace rehab - GP/Medical</option>
            </select>
        </div>
        <div id="div-psych">
            <h2>I need psychological services?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>NDIS - individual employment support</option>
                <option>NDIS - youth</option>
                <option>Judgment Index (as a reseller) - for employers</option>
                <option>Psych Servcies - HR Consulting</option>
                <option>Psych services - EAP - for employer</option>
                <option>Psych services - Mediation / conflict management - for employers</option>
                <option>Psych services - Counselling  / Assessments (e.g. Medicare, WAPHA) - for individual</option>
                <option>Psych services - EAP - for individual</option>
                <option>Psych services for NDIS</option>
                <option>Psych services - Counselling / Assessments (e.g. Medicare, WAPHA) - for GP/Medical</option>
            </select>
        </div>
        <div id="div-employer">
            <h2>Are you an employer?</h2>
            <h3>Let us know what suits you, make your selection below</h3>
            <select>
                <option>Diversity and inclusion for employers</option>
                <option>DES for employers (recruitment)</option>
                <option>H@W for employers</option>
                <option>Judgment Index (as a reseller) - for employers</option>
                <option>Psych Servcies - HR Consulting</option>
                <option>Psych services - EAP - for employer</option>
                <option>Psych services - Mediation / conflict management - for employers</option>
                <option>Training - customised (e.g. OHS, wellness, psych, disability awareness) - for employers</option>
                <option>Training - MHFA - for employers</option>
                <option>Training - Accredited (RTO) - for employers</option>
                <option>Allied Health Physical services for employers</option>
                <option>WR for employers</option>
            </select>
        </div>
    </div>

</div>
0
Suresh Ponnukalai 5 mar. 2018 a las 07:51