1

私はいくつかの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を取得して、parent-xxxからchild-xxxに変更します。次に、その子IDを「表示」します。

これは可能ですか?

4

6 に答える 6

3
$(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/

于 2012-11-07T06:31:05.770 に答える
2

これと同じくらい簡単なもの

var id = $('ul.menu li a.active').attr('id').replace('parent', 'child');
$('#' + id).show();
于 2012-11-07T06:34:28.527 に答える
1
​$('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'));
于 2012-11-07T06:31:01.997 に答える
1

このようなものが機能するはずです:

// 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
于 2012-11-07T06:33:16.640 に答える
0

すべてのli要素をループして、現在のliにアクティブなクラスがあるかどうかを確認する必要があります

デモ

$('ul li').each(function () {
     if($(this).hasClass('active')) {
           // do whatever you want
     }
});
于 2012-11-07T06:29:52.933 に答える
0

最適化されたものではありませんが、これは機能します

$("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/

于 2012-11-07T06:42:39.777 に答える