LoginSignup
3
7

More than 5 years have passed since last update.

loadしたhtmlにjsを適用させる

Last updated at Posted at 2019-02-02

loadしたhtmlにjsを適用させる

前提:フォルダ階層

階層
┣ static
┃ ┣ css
┃ ┃ ┗ menu.css
┃ ┣ js
┃ ┃ ┣common.js
┃ ┃ ┗menu.js
┃ ┣ html
┃ ┃ ┗ menu.html
┗ templates
  ┗ main.html

やりたかったこと

機能

現在いるページと対応するメニューの色を変更させたい。

コード

htmlで複数ページを作る時に、メニューのところのhtmlが長いのでmenu.htmlとして外部ファイルを作った。
それをcommon.jsで読み込み、main.htmlにmenu.htmlを適用させた。
更に今いるページと対応するメニューの色を変更するために
特定のタグをactiveにする処理を書いたmenu.jsをmenu.htmlに適応させたい。

main.html
<body>
    <div id="menu"></div>

    <!--jQueryの読み込みとか-->
    <script type="text/javascript"
        src="/webjars/jquery/3.3.1/jquery.min.js" charset="utf-8">  
    </script>
    <!--javaScriptの読み込み-->
    <script type="text/javascript" src="/js/common.js"></script>
    <script type="text/javascript" src="/js/menu.js"></script>
</body>
menu.html
<ul id="nav"> 
   <li><a href="/menu1">MENU1</a></li> 
   <li><a href="/menu2">MENU2</a></li> 
   <li><a href="/menu3">MENU3</a></li> 
   <li><a href="/menu4">MENU4</a></li> 
 </ul> 
common.js
$(window).on('load', function() {
      //main.htmlのmenu要素についてmenu.htmlを適用させる
    $("#menu").load('/html/menu.html');
});
menu.js
//現在のページのurlとメニューのurlが同じだったら、そこのタグをactiveにする
$(function() {
    $('#nav li a').each(function() {
        var $href = $(this).attr('href');
        if (location.href.match($href)) {
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
});
menu.css
/*activeになってる要素navの[li a]タグの文字を赤にする*/
#nav li a.active {
    color: red;
}

問題1

menu.jsはちゃんと読み込まれているっぽいけど、activeにならない。
コンソール上のエラーは発生してないが、なんかうまく適用されていない気がする

実際にやってみたこと

menu.html上で直接jsを呼んでみる

menu.html
<!--変更したところ↓-->
<script type="text/javascript" src="/js/menu.js"></script>
<!--変更したところ↑-->
<ul id="nav"> 
   <li><a href="/menu1">MENU1</a></li> 
   <li><a href="/menu2">MENU2</a></li> 
   <li><a href="/menu3">MENU3</a></li> 
   <li><a href="/menu4">MENU4</a></li> 
 </ul> 

問題2

とりあえず、jsは読み込まれて適用された。が、
コンソールに以下のエラー

error
[[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

よくわらかないけどエラーが出るってことはダメな気がする。気持ち悪いし
あと、ググったらエンドユーザーに影響がどうのって書いてたらかダメなんだと思う

解決方法

menu.htmlをロードする時に一緒にjsもロードしてあげる!

common.js
$(window).on('load', function() {
      //main.htmlのmenu要素についてmenu.htmlを適用させる
    $("#menu").load('/html/menu.html');
    //変更したところ↓
    $.getScript("/js/menu.js", function() {
    });
    //変更したところ↑
});

これでエラーなくちゃんとactiveにすることができた

参考にしたサイト

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7