我有ul列表,其中有一些li也嵌套了li。
我添加了js,其中li的onclick,它改变了li的bgcolor,但问题是它也扩展到嵌套的li。
我的代码是:
< ul >
< li >
< a > first </ a>
/%nested ul starts here%/
<li>
Nested Word
</li>
</li>
</ul>
JAVASCRIPT:
$('li').click(function(e){
$(this).addClass("active1");
$(this).find('a').addClass("acolor");
});
CSS
.acolor
{
color: #FFFFFF !important;
}
.active1
{
background-color:#536574 !important;
}
问题是当我将bg颜色应用于主div时,它也会通过填充nesed li来附近,这是我不需要的。我只需要bg颜色来应用第一个文本而不是任何地方给它的孩子。
- &GT;我不能改变HTML结构,因为它的代码来自Drupal小部件。
有没有解决方案?
谢谢!
答案 0 :(得分:0)
$('li')
jQuery语句选择DOM中的每个 <li>
,包括您不想选择的 <a>
。如果您只想更改文本元素的背景颜色($('a').click(function(e){
$(this).addClass("active1");
$(this).find('a').addClass("acolor");
});
标签),可以像这样重写语句:
<li>
或者,如果您只想选择<ul>
内的第一个$('ul li:first-child').click(function(e){
$(this).addClass("active1");
$(this).find('a').addClass("acolor");
});
,请选择以下内容:
<a>
答案 1 :(得分:0)
如果你只是想直接在点击的li下选择一个标签,只需使用子选择器“&gt;”这将导致以下javascript:
$('li').click(function(e){
$(this).addClass("active1");
$(this).find('> a').addClass("acolor");
});