2016-07-10 14 views
2

JavaスクリプトまたはJqueryを使用して、アンカータグにクラスを動的に追加しようとしています。私は多くの解決策を見つけましたが、私は何を探していません。私は、PHPの動的ヘッダーとフッターを使用したいです。そのために、私はユーザーが使用する現在のページに「アクティブ」クラスを追加します。PHPでダイナミックにクラスを追加

私を助けてください。

ありがとうございます。

<ul class="nav pull-right"> 
    <li> 
     <a href="index.php"><i class="icon-home"></i><br />Home</a> 
    </li> 
    <li> 
     <a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a> 
    </li> 
</ul> 
+0

//Iterate to navbar $('#mynavbar a').each(function() { //Get attribute href value var href = $(this).attr("href"); //Split by '.' to array var arrhref = href.split('.'); //Get the first portion var hrefportion = arrhref[0]; //Now, we should add class 'active' to the href (also parent li element) //if the 'hrefportion' is equal to 'page' in this case 'portfolio' if (hrefportion == page) { //Add 'active class to the anchor $(this).addClass("active"); //also its parent li element var li = $(this).parent(); li.addClass("active"); } }); 
見る【選択DIVにはJQueryのaddclass(http://stackoverflow.com/questions/18877544/jquery-addclass-to-selected-div-remove-class-if-another-div-is-選択された) – Mohammad

答えて

0
<?php 
$thisPage = "home"; 

?> 
<html> 
<head> 
... 
... 
<body> 
<ul class="nav pull-right"> 
<li <?php if($thisPage == "home") echo 'class="active"'; ?>> 
    <a href="index.php"><i class="icon-home"></i><br />Home</a> 
</li> 
<li> 
    <a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a> 
</li> 

0

この

<?php 

$urlArr = explode("/", $_SERVER['REQUEST_URI']); 

$active_class = array_pop($urlArr); ?> 


<ul class="nav pull-right"> 
    <li class="<?php echo ($active_class == "index.php") ? "active" : ""; ?>"> 
     <a href="index.php"><i class="icon-home"></i><br />Home</a> 
    </li> 
    <li class="<?php echo ($active_class == "portfolio.html") ? "active" : ""; ?>"> 
     <a href="portfolio.html"><i class="icon-camera"></i><br />Portfolio</a> 
    </li> 
</ul> 
0

何か嘘を試してみて、あなたがそのようなことを処理するためのクライアント側をしたい場合は、次のスニペットは、あなたにそれを行うにはどのようにアイデアを与える必要があります。また、URLにindex.phpというURLが表示されているはずです。 htaccessによってほとんどオーバーライドされています。

次の例は、ナビゲーションバーに反復、今http://example.org/portfolio.html

//First, get the current URL 
var url = window.location.href; //output: http://example.org/portfolio.html 

//Then split them to array by '/' 
var arrurl = url.split('/'); //output: Array [ "http:", "", "example.org", "portfolio.html" ] 

//Get last portion of the uri 
var lasturi = arrurl[arrurl.length-1]; //output: portfolio.html 

//Split the last segment by '.' 
var arruri = lasturi.split('.'); //output: Array [ "portfolio", "html" ] 

//Get the first value of previous array 
var page = arruri[0]; //output: portfolio 

のURLを訪問についてです。より良いセレクターのために私はそれにIDを入れました。 <ul id="mynavbar" class="nav pull-right">

関連する問題