2017-09-20 12 views
1

私は自分のウェブサイトのすべての異なるページにロードされたheader.phpに入れ子にしたメニューを持っています。ページのjQuery表示名を

ユーザーが現在訪れているページの名前をjQueryで表示したいとします。名前を表示するdivには、.menu_location_innerクラスが割り当てられています。私はコードがこのように見えるだろうと思った。

$(document).ready(function() { 
    $(".menu_location_inner").html('some code here') 
}); 

DOMにページ名を保存して上記のコードを完成させるにはどうすればよいですか?

+0

ここでページの名前を表示しますか? –

+0

あなたのページの名前はどこから来るのですか?ページのタイトルタグはどこですか? – j08691

+0

名前は私の質問の一部でもありますが、メニューバーに表示する以外の目的では必要ありません。 – Grommit

答えて

1

だけでなく、あなたのページのタイトルタグであることを起こるものは何でも(それはでも、セットの場合) また、jQueryのHTML機能を使用すると、あなたのことを行うためにいくつかの追加の電力を与える:そう...

$(document).ready(function() { 
    var page1 = location.href.match("index.html"); 
    var page2 = location.href.match("contact.html"); 
    var page3 = location.href.match("feedback.html"); 

    if(location.href.match(page1)) { 
    var thisPage = "You're on our main page!" 
    } 

if(location.href.match(page2)) { 
    var thisPage = "You're on our contact page!" 
    } 

if(location.href.match(page3)) { 
    var thisPage = "You're on our feedback page!" 
    } 

    $(".menu_location_inner").html(thisPage); 

}); 

EDITは次のように、あなたは条件付きで、URLに基​​づいて変数に名前を付けることができます。これは参考になるかもしれませんが、コードスニペットの最後の部分をデモするために変更しました。

$(document).ready(function() { 
    var page1 = location.href.match("index.html"); 
    var page2 = location.href.match("contact.html"); 
    var page3 = location.href.match("feedback.html"); 

    if(location.href.match(page1)) { 
    var thisPage = "You're on our main page!" 
    } 

if(location.href.match(page2)) { 
    var thisPage = "You're on our contact page!" 
    } 

if(location.href.match(page3)) { 
    var thisPage = "You're on our feedback page!" 
    } 
    //You can wrap your answer in any tag you'd like 
    //You also have the option to add ID's and/or classes here 
    $(".menu_location_inner").html('<p class="myClass" id="myID">' + thisPage + '</p>'); 

}); 
+0

非常に直感的で実際にページタイトルに接続しているよりも良い解決策 – Grommit

+0

ありがとう、助けてうれしい!! – iPzard

+0

タイトルメッセージにタグやクラスを追加する方法を示すために編集しました。あなたの状況に役立つかもしれません。 – iPzard

0

次のコードは、あなたが望むことをします。それはtitleタグの中からテキストを取得し、クラスmenu_location_innerを持つ要素に書き込み:あなたはカスタムメッセージをしたいと仮定し

$(document).ready(function() { 
    var pagename = $("title").text(); 
    $(".menu_location_inner").text(pagename); 
}); 
+0

はい、魅力的です。ありがとう! – Grommit

関連する問題