@eellazy

Можно ли сократить код?

Всем привет! Можно ли сократить код? А то такой скрипт уж очень слабый. Не думаю что так правильно писать. На каждый клик своё действие

<ul class="device-list">
                <li><button id="desktop-iframe__btn">Десктоп</button></li>
                <li><button id="tablet-iframe__btn">Планшет</button></li>
                <li><button id="tabletland-iframe__btn">Планшет2</button></li>
                <li><button id="phone-iframe__btn">Телефон</button></li>
                <li><button id="phoneland-iframe__btn">Телефон2</button></li>
  </ul>
 <div id="iframelive" class="desktop-iframe">
        <iframe src="https://google.com" frameborder="0">

        </iframe>
    </div>


$("#desktop-iframe__btn").click(function() {
    $(this).parent().addClass('active');
    $("#iframelive").removeClass();
    $("#iframelive").addClass("desktop-iframe");
});

$("#tablet-iframe__btn").click(function() {
    $(this).parent().addClass('active');
    $("#iframelive").removeClass();
    $("#iframelive").addClass("tablet-iframe");
});

$("#tabletland-iframe__btn").click(function() {
    $(this).parent().addClass('active');
    $("#iframelive").removeClass();
    $("#iframelive").addClass("tabletland-iframe");
});

$("#phone-iframe__btn").click(function() {
    $(this).parent().addClass('active');
    $("#iframelive").removeClass();
    $("#iframelive").addClass("phone-iframe");
});

$("#phoneland-iframe__btn").click(function() {
    $(this).parent().addClass('active');
    $("#iframelive").removeClass();
    $("#iframelive").addClass("phoneland-iframe");
});
  • Вопрос задан
  • 96 просмотров
Решения вопроса 1
@Tiasar
Web Developer
Что то на подобии?

<ul class="device-list">
    <li><button data-targetClass="desktop-iframe">Десктоп</button></li>
    <li><button data-targetClass="tablet-iframe">Планшет</button></li>
    <li><button data-targetClass="tabletland-iframe">Планшет2</button></li>
    <li><button data-targetClass="phone-iframe">Телефон</button></li>
    <li><button data-targetClass="phoneland-iframe">Телефон2</button></li>
</ul>


$(".device-list").on("click", "button", function() {
    $(this).parent().addClass('active');
    $("#iframelive")
        .removeClass()
        .addClass($(this).attr('data-targetClass'));
});
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы