striving to make jquery and li working in this context:
<div id="statLateralMenu">
<h3>Statistics</h3>
<ul>
<li id="id1" class="selected">Stat 1</li>
<li id="id2">Stat 2</li>
</ul>
</div>
s
$(function() {
$("#statLateralMenu li").click(function()
{
alert( "A" );
$("#statLateralMenu li").removeClass("selected");
$(this).addClass("selected");
});
}
);
I am pretty sure the error is very stupid also because I've already implemented this code in another area of my page and it works perfectly, but this time really I can't make it working. Any clue please?
EDIT:
I am not able even to fire the alert, my problem is not (yet) to change the class's li
. JQuery is loaded as in the same page I have another ul/li complex and it works perfectly
EDIT 2: At this point maybe I am messing up a bit, but using my code here it doesn't work as well: https://jsfiddle.net/nakjyyaj/4/
It seems to work :
$(function() { $("li").click(function() { $("li").removeClass("selected"); $(this).addClass("selected"); }); });
.selected{background:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>azerty</li> <li>bzerty</li> <li>czerty</li> </ul>
To deal with dynamic content you can use event delegation :
$(function() { $("ul").on("click", "li", function() { $("li").removeClass("selected"); $(this).addClass("selected"); }); }); setTimeout(function () { $("p").remove(); $("ul").html("" + "<li>azerty</li>" + "<li>bzerty</li>" + "<li>czerty</li>" ); }, 1000);
.selected{background:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Wait 1 second.</p> <ul></ul>
Further reading : https://stackoverflow.com/a/46251110/1636522 .
try to change $("#statLateralMenu li").removeClass("selected");
to
$(this).removeClass("selected");
like that
$(function() {
$("#statLateralMenu li").click(function()
{
alert( "A" );
$(this).removeClass("selected");
$(this).addClass("selected");
});
}
);
but if you want only to change design elements you can use :hover
li:hover {
background-color: yellow;
}
In your JSFiddle, you forgot to load JQuery framework. You don't need script tag in JSFiddle (no need and ).
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.