回答編集履歴

3

コード修正

2022/11/29 07:29

投稿

hatena19
hatena19

スコア33620

test CHANGED
@@ -7,9 +7,11 @@
7
7
  あるいは、URLと一致するhrefのメニューを検索してそれにクラスを付加してもいいでしょう。
8
8
 
9
9
  コード例
10
- ```js
10
+ ```JavaScript
11
11
  window.addEventListener("load", function () {
12
+ let url=location.href;
13
+ url = url.substr(url.lastIndexOf('/') + 1);
12
- const currentMenu = document.querySelector(`.js_menu_select[href$="${location.href}"]`);
14
+ const currentMenu = document.querySelector(`.js_menu_select[href$="${url}"]`);
13
15
  currentMenu.classList.add('menu_selected');
14
16
  });
15
17
  ```

2

コードを修正

2022/11/29 07:01

投稿

hatena19
hatena19

スコア33620

test CHANGED
@@ -9,8 +9,7 @@
9
9
  コード例
10
10
  ```js
11
11
  window.addEventListener("load", function () {
12
- const currentMenu = document.querySelector(`.js_menu_select[href="${location.href}"]`);
12
+ const currentMenu = document.querySelector(`.js_menu_select[href$="${location.href}"]`);
13
13
  currentMenu.classList.add('menu_selected');
14
14
  });
15
-
16
15
  ```

1

コード追記

2022/11/29 03:03

投稿

hatena19
hatena19

スコア33620

test CHANGED
@@ -5,3 +5,12 @@
5
5
 
6
6
  現在のページのURLは `location.href`で取得できますので、その値で、Switch文で該当するメニューにクラスを付加するようにすればいいでしょう。
7
7
  あるいは、URLと一致するhrefのメニューを検索してそれにクラスを付加してもいいでしょう。
8
+
9
+ コード例
10
+ ```js
11
+ window.addEventListener("load", function () {
12
+ const currentMenu = document.querySelector(`.js_menu_select[href="${location.href}"]`);
13
+ currentMenu.classList.add('menu_selected');
14
+ });
15
+
16
+ ```