检查href是否有类,如果是,请获取id

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

基本上我有这样的HTML结构。

 

如果用户“打开”,我的PHP代码会添加一个class =“active”,因此根据点击的链接,它将如下所示:

 
  • Four
  • 所以这一切都相当直接。

    我希望能够在页面加载时执行的操作是搜索每个菜单项,直到找到class =“active”的那个..然后获取该链接的ID,将其从parent-xxx更改为child-xxx并且然后’显示’那个孩子的身份证。

    这可能吗?

     $(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, ie 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是否具有活动类

    DEMO

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