[英]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
类,但不会将其从其他项目中删除。
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>
$("#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.