简体   繁体   English

在1个元素上切换类,然后从休息中移除

[英]Toggle class on 1 element and remove from rest

I'm more of a back-end guy, but I got frustrated by this small problem related to front-end. 我更多地是一个后端人员,但是我对与前端相关的这个小问题感到沮丧。

I have a side menu with few links. 我的侧边菜单很少链接。

<div id="sideMenu" class="vertical-menu">
    <a href="#" id="allCategories" class="active" onclick="changeClass(this)">All</a>
    <a href="#" id="fruit" onclick="changeClass(this)">Fruits</a>
    <a href="#" id="vegetables" onclick="changeClass(this)">Vegetables</a>
    <a href="#" id="fish" onclick="changeClass(this)">Fish</a>
    <a href="#" id="meat" onclick="changeClass(this)">Meats</a>
</div>

And I'm trying to toggle active class on click and remove it from another menu items 我试图在单击时切换active类并将其从另一个菜单项中删除

<script>
    function changeClass(element) {
        $('#sideMenu').each(function(){
            var theID = $(this).attr('id');
            var menuElement = document.getElementById(theID);
            menuElement.classList.remove('active')
        });
        $(element).toggleClass('active');
    }
</script>

I've tried few other ways and it all fails, it toggles active class on the new item, but it doesn't remove it from other ones. 我尝试了其他几种方法,但都失败了,它会在新项目上切换active类,但不会将其从其他项目中删除。

EDIT 编辑

I've ran into another problem. 我遇到了另一个问题。

 <div id="sideMenu" class="vertical-menu">
    <a href="/productsTable" id="allCategories" class="active">All</a>
    <a href="/productsTableCategory?id=1" id="fruit">Fruits</a>
    <a href="/productsTableCategory?id=2" id="vegetables">Vegetables</a>
    <a href="/productsTableCategory?id=3" id="fish">Fish</a>
    <a href="/productsTableCategory?id=4" id="meat">Meat</a>
</div>

 <script>
    $("#sideMenu a").click(function(e){
        e.preventDefault();
        $("#sideMenu a.active").removeClass("active");
        $(this).addClass("active");
    })
</script>

and back-end side 和后端

private ProductRepository productRepository;
    private ProductCategoryRepository productCategoryRepository;

@Autowired
public ProductsTableController(ProductRepository productRepository, ProductCategoryRepository productCategoryRepository) {
    this.productRepository = productRepository;
    this.productCategoryRepository = productCategoryRepository;
}

@RequestMapping("/productsTable")
    public String showProductsTable(Model model){
        Iterable<Product> products = productRepository.findAll();
        model.addAttribute("products", products);
        return "productsTable";
    }

@RequestMapping("/productsTableCategory")
    public String showProductsTable(Model model, @RequestParam int id) {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setId(id);
        Iterable<Product> products = productRepository.findByProductCategory(productCategory);
        model.addAttribute("products", products);
        return "productsTable";
    }

Now it works almost perfect... almost because if I directly open localhost:8080/productsTableCategory?id=1 for example I'll have my table sorted by given id. 现在它几乎可以正常工作了……几乎是因为,例如,如果我直接打开localhost:8080/productsTableCategory?id=1 ,我将按照给定的ID对我的表进行排序。 But when I try to open this by clicking 1 of links from my sidemenu, it isn't redirecting me anywhere 但是,当我尝试通过单击侧面菜单中的链接之一来打开它时,它没有将我重定向到任何地方

You need to target anchor elements, excluding the current element ie element using the function .not() , then use .removeClass() . 您需要定位锚元素,不包括当前元素,即使用功能.not() element ,然后使用.removeClass() And use id selector with sideMenu element ie #sideMenu 并将id选择器与sideMenu元素(即#sideMenu

function changeClass(element) {
    $('#sideMenu a').not(element).removeClass('active')
    $(element).toggleClass('active');
}

I would recommend you to use unobtrusive event handler and bind event using jQuery's .on() method 我建议您使用不显眼的事件处理程序,并使用jQuery的.on()方法绑定事件

$('#sideMenu a').on('click', function (e) {
    e.preventDefault();
    $('#sideMenu a').not(this).removeClass('active')
    $(this).toggleClass('active');
})

and remove onclick="changeClass(this)" 并删除onclick="changeClass(this)"

 $('#sideMenu a').on('click', function(e) { e.preventDefault(); $('#sideMenu a.active').not(this).removeClass('active') $(this).toggleClass('active'); }) 
 .active { color: red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="sideMenu" class=" vertical-menu"> <a href="#" class="active">All</a> <a href="#">Fruits</a> <a href="#">Vegetables</a> <a href="#">Fish</a> <a href="#">Meats</a> </div> 

  1. First remove the class active from the anchor. 首先从锚中删除活动类。
  2. Then add the class to the clicked element. 然后将该类添加到clicked元素中。

 $("#sideMenu a").click(function(e){ e.preventDefault(); $("#sideMenu a.active").removeClass("active"); $(this).addClass("active"); }) 
 .active { color: red } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="sideMenu" class="vertical-menu"> <a href="#" id="allCategories" class="active">All</a> <a href="#" id="fruit">Fruits</a> <a href="#" id="vegetables">Vegetables</a> <a href="#" id="fish">Fish</a> <a href="#" id="meat">Meats</a> </div> 

Just need to change selector in your code: 只需更改代码中的选择器即可:

<script>
    function changeClass(element) {
        $('a').each(function(){        // Here a is used. It will loop through all anchor tags and apply the JQ.
            var theID = $(this).attr('id');
            var menuElement = document.getElementById(theID);
            menuElement.classList.remove('active')
        });

        $(element).toggleClass('active');
    }
</script>

In pure javascript you can do it like this. 在纯JavaScript中,您可以这样操作。

<div id="sideMenu" class="vertical-menu">
    <a href="#" id="allCategories" class="active" >All</a>
    <a href="#" id="fruit" >Fruits</a>
    <a href="#" id="vegetables" >Vegetables</a>
    <a href="#" id="fish" >Fish</a>
    <a href="#" id="meat" >Meats</a>
</div>

and a js code. 和一个js代码。

var links = document.querySelectorAll('#sideMenu a');


// removes active class from all links
function removeAll() {
    for (let i = 0; i < links.length; i++)
        links[i].className = '';
}

// adds active class to the clicked link, 
// but before it removes it from all other links
for (let i = 0; i < links.length; i++) {
    links[i].addEventListener('click', event => {
        removeAll();
        links[i].className = 'active';
    });
}

It may help you to make your menu active. 它可以帮助您激活菜单。 Here window.sessionStorage is used..! 这里使用window.sessionStorage ..!

$("#sideMenu a").on('click', function(ev) {
    ev.preventDefault();
    window.sessionStorage.removeItem('activeMenu');
    window.sessionStorage.setItem('activeMenu', $(this).attr('href'));
    window.location.href = $(this).attr('href');
});

//check on redirected page (In your case productsTableCategory page)
$(document).ready(function() {
    if (window.sessionStorage.length > 0) {
        var menuToActive = window.sessionStorage.getItem('activeMenu');
        $("#sideMenu a.active").removeClass('active'); //comment this line to keep all menus active by default
        $('[href="' + menuToActive + '"]').addClass('active');
        window.sessionStorage.removeItem('activeMenu');
    } else {
        $('#allCategories').addClass('active');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Vanilla Javascript:如果单击具有相同切换类的Y元素,则从X元素中删除切换类 - Vanilla Javascript: Remove toggle class from X element if I click on Y element with the same toggle class 从所有元素中删除类,然后在所选元素上切换 - Remove class from all elements and then toggle it on selected element jQuery:在一个元素上切换类,从所有其他元素上删除类 - jQuery: Toggle class on one element, remove same from all other 如何在单击元素时切换类,但使用 JQuery 从所有其他元素中删除相同的类? - How do I toggle a class on click of an element but remove the same class from all other elements using JQuery? 无法将元素的类别删除/切换回“ is-inactive” - Unable to remove/toggle class of element back to `is-inactive` 无法在Vue指令中添加/删除/切换元素类? - Cannot add/remove/toggle element class inside Vue directive? 单击元素本身时切换类,单击外部时删除 - Toggle Class when click on element itself and remove when click outside 使用切换元素(jQuery)动态添加/删除另一个表中的元素 - Dynamically add/remove an element from another table with a toggle element (jQuery) 在生成的切换元素上切换类 - Toggle class on generated toggle element Javascript-从元素(不带ID /类)中删除句子,但保留其余内容 - Javascript - remove a sentence from an element (w/o id/class) but leave the rest of the content
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM