回答編集履歴

2

:has\(\)

2017/04/19 16:26

投稿

think49
think49

スコア18166

test CHANGED
@@ -12,4 +12,28 @@
12
12
 
13
13
 
14
14
 
15
+ ---
16
+
17
+
18
+
19
+ > 正確には、liの方にクラスを付与したかったので、「.parent('li')」を加えてうまくいきました。
20
+
21
+
22
+
23
+ 親のli要素にマッチさせたいのなら、`:has()` を併用すれば `jQuery#parent` を利用しなくて済みます。
24
+
25
+
26
+
27
+ ```JavaScript
28
+
29
+ jQuery('li:has(a[href="' + location.pathname + '"])').addClass('current');
30
+
31
+ jQuery('li:has(a[href="' + location.pathname.replace(/[^/]*$/, '') + '"])').addClass('current');
32
+
33
+ ```
34
+
35
+
36
+
37
+
38
+
15
39
  Re: umauman さん

1

コードの最適化

2017/04/19 16:26

投稿

think49
think49

スコア18166

test CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
  jQuery('a[href="' + location.pathname + '"]').addClass('current');
8
8
 
9
- jQuery('a[href="' + location.pathname.replace(/\/[^/]*$/, '/') + '"]').addClass('current');
9
+ jQuery('a[href="' + location.pathname.replace(/[^/]*$/, '') + '"]').addClass('current');
10
10
 
11
11
  ```
12
12