内包する子要素のリンクを別子要素にも適用したいです。
具体的には、以下の構成で「hoge1」をクリックすると「hoge2」と同じURLに移動したいです。
lang
1<div class="hoge"> 2<div class="hoge1"></div> 3<a href="XXXXXXX" class="hoge2"></a> 4</div>
hogeは連続して複数存在し、それぞれのhoge内で処理したいので「.each」を使用した形でご教授願えればと思います。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答2件
0
ベストアンサー
先の回答されたものとほぼ同じですが。ご参考までに。
html
1<div class="hoge"> 2 <h3>test: ヤフー</h3> 3 <div class="hoge1">hoge1</div> 4 <a href="http://www.yahoo.co.jp/" class="hoge2">hoge2</a> 5</div> 6 7<div class="foo"> 8 <h3>test: DOM構造が異なるケース</h3> 9 <div class="hoge1">hoge1</div> 10 <a href="http://www.rakuten.co.jp/" class="hoge2">hoge2</a> 11</div> 12 13<h3>test: DOM構造が異なるケース2</h3> 14<div class="hoge1">hoge1</div> 15<a href="http://www.rakuten.co.jp/" class="hoge2">hoge2</a> 16 17<div class="hoge"> 18 <div class="foo"> 19 <h3>test: DOM構造が異なるケース3</h3> 20 <div class="hoge1">hoge1</div> 21 <a href="http://www.rakuten.co.jp/" class="hoge2">hoge2</a> 22 </div> 23</div>
js
1$(function() { 2 // hoge1がクリックされたら、親のdiv.hogeのa.hoge2のhrefを取得し、そこへ遷移させる 3 var link; 4 $('.hoge1').on('click', function(e){ 5 // .hogeの中の.hoge2へアクセスし、hrefの値を取得 6 link = $(this).parents('.hoge').find('.hoge2').attr('href'); 7 console.log('link: ', link); 8 // linkの値が取得できていれば、リンク先に遷移させる 9 if (link !== undefined) { 10 window.location.href = link; 11 } 12 }); 13});
link = $(this).parents('.hoge').find('.hoge2').attr('href')
ここの部分ですが、
.hoge2
の1つ親が必ず.hoge
であるならば、
$(this).parent()
でも良いですが、
$(this).parents('.hoge')
の方が、他のケースも担保できるので良さそうです。
下記ご参考までに。
http://qiita.com/yamamoto_hiroya/items/358c55db38c481a2c1b0
http://tohokuaiki.hateblo.jp/entry/20120912/1347443736
投稿2015/11/08 16:39
編集2015/11/08 16:41総合スコア290
0
下記でどうでしょうか。「.each」は必要ないですね。
自分の親要素内の子要素から a要素のURLを取得してページ遷移するということです。
html
1<div class="hoge"> 2 <div class="hoge1">hoge1</div> 3 <a href="https://www.google.co.jp/" class="hoge2">google</a> 4</div> 5<br> 6<div class="hoge"> 7 <div class="hoge1">hoge1</div> 8 <a href="http://www.yahoo.co.jp/" class="hoge2">yahoo</a> 9</div>
javascript
1$(function() { 2 $('.hoge div').click(function() { 3 window.location.href = $(this).parent().children('a').attr("href"); 4 }); 5});
投稿2015/11/08 07:10
総合スコア33715
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/13 02:27