我已经编写代码使 li 在 url 的基础上处于事件状态。它工作正常但它在子 li 上失败。它使子 li 处于事件状态,而我希望 top li 应该处于事件状态而不是 child。我的代码如下:
<script type="text/javascript">
jQuery(function () {
setNavigation();
});
function setNavigation() {
// this portion code make li active on url basis
var pathname = window.location.pathname;
path = pathname.replace(/\/$/, "");
path = decodeURIComponent(path);
var value = jQuery(location).attr('href');
// value = value.replace('.html', ''); alert(value);
jQuery(".flexy-menu a").each(function () {
var href = jQuery(this).attr('href');
if (value === href) {
jQuery(this).closest('li').addClass('active');
}
});
// this is code for child li but only first code works
jQuery('.flexy-menu').children('li').click(function(){
jQuery(this).parent('li').addClass('active');
});
}</script>
我的 HTML 是这样的:
<ul class="flexy-menu orange">
<li style=""><a href="http://example.com/">Home</a></li>
<li style=""><a href="JavaScript:void(0)">Collection</a>
<ul style=""> <li><a href="http://example.com/my-secret-garden.html">My Secret Garden </a></li>
<li><a href="http://example.com/legend.html">Legend</a></li></ul>
</li>
<li class="active" style=""><a href="http://example.com/artisans">Artisans</a></li>
<li style=""><a href="http://example.com/contacts">Contact </a></li>
</ul>
最佳答案
代替父级使用 .closest()
:
jQuery(this).closest('li').addClass('active');
并将其放入文档中:
jQuery(function () {
setNavigation();
jQuery('.flexy-menu').find('li').click(function(){
jQuery(this).closest('li').addClass('active');
});
});
这里我用 .find()
而不是 .children()
稍微改变了你的选择器,因为 .find()
寻找孙子也是,如果你想遍历到父级,那么使用 .closest()
方法。
我已经编写代码使 li 在 url 的基础上处于事件状态
好的!然后你可以选择这样做:
$('a[href*="'+ path +'"]').parents('li').addClass('active');
这应该有效:
总而言之,你只需要这样做,不需要额外的功能:
jQuery(function () {
var path = window.location.pathname;
$('a[href*="'+ path +'"]').parents('li').addClass('active');
jQuery('.flexy-menu').find('li').click(function(){
jQuery(this).closest('li').addClass('active');
});
});
关于javascript - jquery 中的子 li 选择未选择 li 父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096199/