I have this nav menu:
<ul>
<li class="click-li" id="tray-active"><a href="/">Home</a></li> <!-- Active page -->
<li class="click-li"><a href="/news">News</a></li>
<li class="click-li"><a href="/products">Products</a></li>
<li class="click-li"><a href="/sales">General Sales T and C</a></li>
<li class="click-li"><a href="/jobs">Job Opportunities</a></li>
<li class="click-li"><a href="/inquire">Inquiry</a></li>
</ul>
When the anchor is clicked it will re-load the page (since my site is based on a CMS). So I am guessing this is the reason why this code would not work:
$(document).ready(function(){
console.log("document ready");
$("#tray li").removeAttr("id");
$('.click-li').live('vclick', function() {
var subMenuItem = $(this).text();
alert('Sub Menu Item: '+subMenuItem);
});
});
My main goal is to set the clicked tray li
id
attribute to "tray-active"
so the CSS for active nav
will be applied.
Update:
Ok so this worked:
$('.click-li').on('click', function() {
var subMenuItem = $(this).text();
alert('Sub Menu Item: '+subMenuItem);
});
Still having problem since when the page reloads, after clicking on of the nav menu, the selected li
gets its "active" css style, how do I iterate over the other .click-li
except for the one pointed by $(this)
so I can remove their id's?
I think this is what you are looking after
$(document).ready(function(){
console.log("document ready");
$('.click-li').click(function(event) {
event.preventDefault();
$(".click-li").removeAttr("id");
var subMenuItem = $(this).text();
alert('Sub Menu Item: '+subMenuItem);
$(this).attr("id", "tray-active");
});
});
Use event.preventDefault: http://api.jquery.com/event.preventDefault/ This will keep the page from re-loading when you click on the anchor tag. Also, consider using .on as .live is deprecated.
$('ul').on('click', '.click-li', function(e) {
e.preventDefault();
var subMenuItem = $(this).text();
alert('Sub Menu Item: '+subMenuItem);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.