Это повторение кода и желание минимизировать JQuery - PullRequest
1 голос
/ 09 октября 2019

Я написал JQuery, но есть повторение строк кода. Я хочу минимизировать эти строки кода. Понятия не имею, как это сделать? Может ли кто-нибудь помочь мне будет признателен.

HTML

<div class="content-wrapper">
    <div class="publish-content">
        <div class="content-title">
            <h5>Publised content</h5>
            <span><img src="images/accordion-arrow.png" alt="down arrow"/></span>
        </div>
        <div class="content">
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><hr>
        </div>
    </div>

    <div class="upcoming-content">
        <div class="content-title">
            <h5>Upcoming content</h5>
            <span><img src="images/accordion-arrow.png" alt=" down arrow"/></span>
        </div>
        <div class="content">
            <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><hr>
        </div>
    </div>
</div><!--content section ends---------->

Обратите внимание: я удалил здесь HTML будущего содержания.

jquery

$('.publish-content').click(function() {
    var clicks = $(this).data('clicks');
    if (clicks) {
        // odd clicks
        $(this).children('.content').slideUp();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    } else {
        // even clicks
        $(this).children('.content').slideDown();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(90deg)'});
        $('.upcoming-content').children('.content').slideUp();
        $('.upcoming-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
        $('.future-content').children('.content').slideUp();
        $('.future-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    }
    $(this).data("clicks", !clicks);
});
$('.upcoming-content').click(function() {
    var clicks = $(this).data('clicks');
    if (clicks) {
        // odd clicks
        $(this).children('.content').slideUp();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    } else {
        // even clicks
        $(this).children('.content').slideDown();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(90deg)'});
        $('.publish-content').children('.content').slideUp();
        $('.publish-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
        $('.future-content').children('.content').slideUp();
        $('.future-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    }
    $(this).data("clicks", !clicks);
});

Обратите внимание: я удалил здесь jquery из будущего контента. Вот и все.

Ответы [ 2 ]

1 голос
/ 09 октября 2019

Просто объедините функцию вместе

Если код одинаков в обоих событиях щелчка:

$('.publish-content, .upcoming-content').click(function() {...});

Если части кода совпадают, перейдите к функциям:Например:

function xyz(){
    $(this).children('.content').slideUp();
    $(this).children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
}

А затем используйте xyz(); везде, где вы хотите выполнить.

$('.publish-content').click(function() {
    var clicks = $(this).data('clicks');
    if (clicks) {
        // odd clicks
        xyz();
    } else {
        // even clicks
        $(this).children('.content').slideDown();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(90deg)'});
        $('.upcoming-content').children('.content').slideUp();
        $('.upcoming-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
        $('.future-content').children('.content').slideUp();
        $('.future-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    }
    $(this).data("clicks", !clicks);
});

Надеюсь, это поможет!

0 голосов
/ 09 октября 2019

Вы можете использовать запятую, чтобы связать обработчик события щелчка для нескольких элементов. пользователь attr('class'), чтобы получить имя класса и использовать его в своем скрипте. таким образом, вы можете обобщить скрипт и минимизировать ваш код

$('.publish-content, .upcoming-content').click(function() {
    var className = $(this).attr('class');
    var clicks = $(this).data('clicks');
    if (clicks) {
        // odd clicks
        $(this).children('.content').slideUp();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    } else {
        // even clicks
        $(this).children('.content').slideDown();
        $(this).children('div:first').children('span').css({'transform' : 'rotate(90deg)'});
        $('.' + className).children('.content').slideUp();
        $('.' + className).children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
        $('.future-content').children('.content').slideUp();
        $('.future-content').children('div:first').children('span').css({'transform' : 'rotate(0deg)'});
    }
    $(this).data("clicks", !clicks);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...