【jQuery】リンクを別ウィンドウで開くかtarget="_blank"の判別と動作の分岐
目次
別ウィンドウで開く・開かないで異なる方法
グローバルメニューに設置したメガメニューのリンクを開く際、Javascriptでwindow.location.href
を実行しないとリンクが開かないことがありました。ただ、window.location.href
だと、target="_blank"
があるリンクの場合、別ウィンドウが開かず、同じウィンドウで開いてしまいます。調べてみたところ、target="_blank"
があるリンクの場合はwindow.open
を使わないといけないことがわかりました。
ソース例
同ウィンドで開くとき
window.location.href
を使用する。
$( '#menu_list a' ).on( 'click mouseend touchend' , function () { window.location.href = 'https://example.com' ; }); |
別ウィンドで開くとき
window.open
を使用する。
$( '#menu_list a' ).on( 'click mouseend touchend' , function () { window.open( 'https://example.com' , '_blank' ); }); |
target="_blank"を判別して実行する例
このソースで解決できました。
$( '#menu_list a' ).on( 'click mouseend touchend' , function () { let link = $( this ).attr( 'href' ); let linktarget = $( this ).attr( 'target' ); // target="_blank"の有無を判別 if ( linktarget == '_blank' ) { window.open(link, linktarget); } else { window.location.href = link; } $(document).blur(); }); }); |