I want to change the color of li which contains anchor when the mouse g开发者_StackOverflow中文版o over it, I make like this
<ul id="SonsItemList">
<li class="sonItem"><a id="son" href="#" >son 1</a></li>
<li class="sonItem"><a id="son" href="#" >son 2</a></li>
</ul>
and jquery is
$(document).ready(function(){
$("a#son").hover(function(){
$("li.sonItem").css("background-color","black"); // it make all li background => black
});
I just want the li that the mous go over to change it's background, how can I make it ? });
You don't need any JavaScript at all. You can use CSS:
li.sonItem:hover
{
background-color: black;
}
Do it like this:
$("a[id='son']").hover(function(){
$(this).closest("li.sonItem").css("background-color","black");
});
NOTE: This will work ok, however you should never have more than 1 element with the same id (you can, but it's a very, very bad practice), it'd be better if you use a class, for example class="son"
, and your selector would be $("a.son")
.
Cheers
If you're wanting a nice hover effect then you'll want jquery, you'll also need jquery-color.js, the code is below:
<script type="text/javascript">
$(function () {
$('#menu .dummyclass').mouseover(function () {
$(this).animate({
backgroundColor: '#FF0000'
}, 50, function () { });
});
});
$(function () {
$('#menu .dummyclass').mouseleave(function () {
$(this).animate({
backgroundColor: '#000000'
}, 600, function () { });
});
});
</script>
HTML Markup:
<div id="menu">
<ul>
<li class="dummyclass">Home</li>
<li class="dummyclass">Fixtures</li>
<li class="dummyclass">Results</li>
<li class="dummyclass">Tables</li>
<li class="dummyclass">Constitution</li>
<li class="dummyclass" style="border-right: none;">Contact Us</li>
</ul>
</div>
CSS:
#menu ul li .dummyclass {
/*Dummy class to aid hovering with jQuery*/
}
Id is unique so dont repeat, u can use in class
$(document).ready(function(){
$(".son").hover(function(){
$(".sonItem").css("background-color","black");
},function(){
$(".sonItem").css("background-color","white");
});
});
<ul id="SonsItemList">
<li class="sonItem"><a class="son" href="#" >son 1</a></li>
<li class="sonItem"><a class="son" href="#" >son 2</a></li>
</ul>
精彩评论