Я новичок в jQuery. У меня есть функциональность, которую я хочу, но я уверен, что мой код jQuery может быть значительно упрощен - много повторений.

Например, каждый щелчок приводит к почти одинаковому результату - чтобы скрыть 7 делений и показать 1. Я предполагаю, что есть способ переключать все деления одновременно.

Пожалуйста, укажите мне в правильном направлении, как упростить JQuery.

Спасибо. Онлайн-версия страницы находится здесь.

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 Мар 2018 в 10:26

4 ответа

Лучший ответ

Вы можете выбрать кратные, так что это:

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

Становится

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

Прополощите и повторите с другими, и это будет намного проще

Вы также должны сделать отдельные функции для показа / скрытия и т. Д., Которые повторяются, поэтому вместо вызова большого количества селекторов, вызовите функции

Итак, из этого:

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

Мы идем в:

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

И оберните это в свою собственную функцию:

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

Так что, где они должны быть скрыты, вы просто звоните:

hideDivs();

Вы можете сделать гораздо больше, но это только начало

1
Darren Sweeney 5 Мар 2018 в 07:30

Я бы рекомендовал использовать data- атрибуты и селекторы для них. Идентификаторы и классы лучше хранить для использования CSS.

Это становится:

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

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

Тогда на стороне сценария:

$('[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 Мар 2018 в 08:27

Таким образом, вы можете дать всем этим элементам div и li общий класс, такой как

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

Это уменьшит все jquery до

$('.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");
            }
        })
    });
})

Это не проверено, поэтому могут возникнуть ошибки. Должен дать вам хорошую идею, хотя. Вы также можете добавить атрибут html, указывающий на другой div, чтобы избежать необходимости создавать имя в javascript

0
hwhite4 5 Мар 2018 в 07:53

Вы можете использовать некоторые общие селекторы, потому что вы используете id и должны быть уникальными. Посмотрите на мой код ниже.

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

В приведенном выше коде сначала я делаю событие click распространенным, используя $('#selector li').on('click', function(){ вместо каждого щелчка. Далее из структуры вашего HTML li и эквивалентные div имеют одинаковые имена, кроме слова div-. Итак, я создал одну переменную и получил id текущего элемента, по которому щелкнули, и добавил div- для нацеливания текущего div на show.

Теперь я сокращаю повторяющийся код removeClass/hide, используя $("#selector li").removeClass("active"); и $("#selection > div").hide();. Символ > будет нацелен на прямых потомков конкретного element. В нашем случае все div являются прямыми потомками для #selection. Наконец, я показываю текущий div и добавляю класс active для текущего элемента.

$('#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 Мар 2018 в 07:51