gpt4 book ai didi

javascript - jQuery 在页面加载时将事件类添加到父级

转载 作者:行者123 更新时间:2023-12-03 07:00:25 24 4
gpt4 key购买 nike

enter image description here(所有 child 都处于事件状态,如图所示)我想在单击其子级时将 class="active"添加到父级。我设法将类“active”添加到父类,但所有子类也添加了类=“active”。我想要的只是所选的 child 及其 parent 是“活跃的”。

Jquery:

$(document).ready(function(){
var pathname = window.location.pathname;
var filename=pathname.replace(/^.*[\\\/]/, '');

var currentLink=$('a[href="' + filename + '"]'); //Selects the proper a tag
currentLink.parents('.doctormenu').find('li a').removeClass('active');
currentLink.parentsUntil('.doctormenu', 'li').addClass('active');
//currentLink.parent().addClass("active");
//alert(filename);
})

HTML:

<ul class="doctormenu">
<li><a href="index.html" class="active">home</a></li>
<li><a href="testabout.php">about</a></li>
<li><a href="testdisease.php">Disease</a></li>
<li><a href="login.html">Search</a></li>




<li><a href="#" >
Services</a>
<ul>
<li><a href="asdqq.html">Self Diagnosis</a></li>
<li><a href="testservice.php">Online Consultation</a></li>
<li><a href="#">Clinic Appointment</a></li>
</ul>
</li>
</ul>

最佳答案

这是 fiddle有适当的演示

重要的代码是这样的:

// you can change this on.hashchange for the on.documentready
$(window).on('hashchange', function () {
// select a reference, in your case can be the pathname or whatever
var ref = location.hash
// find the matching element
var $el = $('a[href="' + ref + '"]')
// and it's closest parent (avoid select other
// parents and it's less risky than .parent)
var $menu = $el.closest('.doctormenu')

// remove previous active, if there's any
// (may you don't need this if the page is reloading)
$('.doctormenu')
.removeClass('active')
.find('a')
.removeClass('active')

// execute the needed operations, adding class in this example
$el.addClass('active')
$menu.addClass('active')
});

关于javascript - jQuery 在页面加载时将事件类添加到父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37087582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com