jquery if elseif control shortcut

孤者浪人 提交于 2021-02-11 12:51:00

问题


I have a radio input and whichever is chosen I make "#mains" removeclass and addclass, but the conditions will be too high. How can I make the conditions properly. ?

For now, I am just deleting "navbar-sticky" and I will write conditions for reverse situations. There will be very long conditions for it. Thank you in advance for your assistants.

let navbar_type = $('input[name=navbar-type]')


navbar_type.on('click', function () {
        let navbarChecked = $(this).val();

        if (navbarChecked === 'hidden')
            $('#mains').removeClass("navbar-sticky").addClass("menu-hidden")
        else if (navbarChecked === 'static')
            $('#mains').removeClass("navbar-sticky").addClass("navbar-static")
        else if (navbarChecked === 'floating')
            $('#mains').removeClass("navbar-sticky").addClass("navbar-floating")
        else
            $('#mains').removeClass("navbar-sticky").addClass("navbar-sticky")
    })

回答1:


.addClass() and .removeClass() accept strings that are space-separated lists of classes.

data- attributes let you attach data to elements. This can be used to determine what class a particular radio button controls.

Remove all classes, then add the one of interest.

const $target = $('.target');
const $display = $('.display');
const $colors = $('input[type=radio][name=color]');
const classes = $colors.map((i,e) => e.dataset.class).toArray().join(' ');
$colors.on('change', evnt => {
  $target.removeClass(classes).addClass(evnt.target.dataset.class);
  $display.html($(evnt.target).val());
});
.red { background: red; }
.green { background: green; }
.blue { background: cyan; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="display">red</div>
<div class="target red">
<input type="radio" name="color" value="red" data-class="red" checked>
<label for="red">Red</label>
<input type="radio" name="color" value="green" data-class="green">
<label for="green">Green</label>
<input type="radio" name="color" value="blue" data-class="blue">
<label for="red">Blue</label>
</div>



回答2:


let navbar_type = $('input[name=navbar-type]');
navbar_type.on('click', function () {
    let currentValue = $(this).val();
    if (currentValue === 'sticky') {
       return;
    }
    $('#mains').removeClass("navbar-sticky").addClass("navbar-" + currentValue);

});


来源:https://stackoverflow.com/questions/65448843/jquery-if-elseif-control-shortcut

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!