javascript $(this).addClass() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7279720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
$(this).addClass() not working
提问by Dan Clash
I can do $(this).children("a").addClass("class")
and it works fine, but when I do $(this).addClass("class")
it is not working. I am using $(this)
within a mouseover function.
我可以做$(this).children("a").addClass("class")
并且它工作正常,但是当我这样做时$(this).addClass("class")
它不起作用。我$(this)
在鼠标悬停功能中使用。
$("#site nav li.hasChild").mouseover(function ()
{
$(this).children("a").addClass("selectedTab"); // works fine
$(this).addClass("selectedFixTab"); // does not work
$(this).children("ul").css("display", "block");
});
HTML:
HTML:
<header id="site">
<nav>
<ul>
<li id="Li1" class="hasChild">
<a href="#">Fix</a>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
</ul>
</li>
<li id="Li2" class="hasChild">
<a href="#">Learn</a>
<ul>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</li>
<li id="Li3">
<a href="contact.htm">Contact</a>
</li>
</ul>
</nav>
</header>
CSS:
CSS:
.selectedFixTab
{
border-top:1px solid #eb7c00;
border-left:1px solid #eb7c00;
border-right:1px solid #eb7c00;
}
.selectedLearnTab
{
border-top:1px solid #2d70a3;
border-left:1px solid #2d70a3;
border-right:1px solid #2d70a3;
}
.selectedTab
{
border-bottom:1px solid #fff;
}
回答by jfriend00
It successfully adds the "selectedFixTab"
class to the top level LI tags as soon as the mouse hovers over the LI tag. You can see it in action here in this jsFiddle: http://jsfiddle.net/jfriend00/mj2u6/.
"selectedFixTab"
只要鼠标悬停在 LI 标签上,它就会成功地将该类添加到顶级 LI 标签。你可以在这个 jsFiddle 中看到它的实际效果:http: //jsfiddle.net/jfriend00/mj2u6/。
I'm not sure it's doing exactly what you intend, but it is doing what the code says to do. If you care to explain what you're trying to accomplish, we can likely help you fix the code to do what you want.
我不确定它是否完全按照您的意图行事,但它正在按照代码所说的去做。如果您想解释您要完成的任务,我们可能会帮助您修复代码以执行您想要的操作。
回答by mahulst
$("#site nav li a").mouseover(function ()
{
$(this).children("a").addClass("selectedTab"); // works fine
$(this).addClass("selectedFixTab"); // does not work
$(this).children("ul").css("display", "block");
});
I think this is what you want it to do!
我想这就是你想要它做的!