检查HREF是否有上课,如果是,请抓住ID



我正在寻找一些jQuery代码的帮助。

基本上我有一个类似的HTML结构。

<ul class="menu">
    <li><a href="#" id="parent-one">One</a></li>
    <li><a href="#" id="parent-two">Two</a></li>
    <li><a href="#" id="parent-three">Three</a></li>
    <li><a href="#" id="parent-four">Four</a></li>
</ul>

我的php代码在用户在'上'上添加class =" active",因此取决于单击哪些链接,它看起来像这样:

<li><a href="#" class="active" id="parent-four">Four</a></li>

所以这一切都相当简单。

我想在页面加载上可以做的事情是浏览每个菜单项,直到找到一个class =" active"的菜单。然后获取该链接的ID-xxx,然后"显示"该子ID。

这是可能的吗?

$(function() {
    // Within .menu, find .active, grab its id, and replace parent with child
    var new_id = $('.menu').find('.active').attr('id').replace('parent', 'child');
    // Select element with this new id, and show it.
    $('#' + new_id).show();
});​

小提琴:http://jsfiddle.net/rwgjc/1/

与此

一样简单的东西
var id = $('ul.menu li a.active').attr('id').replace('parent', 'child');
$('#' + id).show();

类似的东西应该有效:

// get the link with class 'active'
var activeLink = $('.menu li a.active');
// determine the new id, i.e. child-xyz
var newID = 'child-' + activeLink.attr('id').split('-')[1];
// assign that to the active link
activeLink.attr('id', newID);
// do other stuff with newID
​$('ul li a').each(function(){
  if($(this).hasClass('active')){
      alert($(this).prop('id')); //your action here
  }
});​​​
//or as  techfoobar suggested
alert($('ul.menu li a.active').prop('id'));

不是优化的,但这将起作用

$("ul.menu li").each(function(){
a=$(this).find('a');
if(a.hasClass('active')){
id=a.attr('id');
a.attr('id',"child-"+id.split("-")[1]);
}
});

工作演示:http://jsfiddle.net/scufp/

您需要循环遍历所有LI元素,并检查当前LI是否具有Active

类别

演示

$('ul li').each(function () {
     if($(this).hasClass('active')) {
           // do whatever you want
     }
});

最新更新