target =“ _blank”を追加する方法指定されたdiv内のリンクへ?
-
03-07-2019 - |
質問
次のコードがあるとしましょう:
<div id="link_other">
<ul>
<li><a href="http://www.google.com/">google</a></li>
<li>
<div class="some_class">
dsalkfnm sladkfm
<a href="http://www.yahoo.com/">yahoo</a>
</div>
</li>
</ul>
</div>
この場合、JavaScriptはdiv link_other
内のすべてのリンクに target =&quot; _blank&quot;
を追加します。
JavaScriptを使用してこれを行うにはどうすればよいですか
解決
/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
$('#link_other a').attr('target', '_blank');
});
// not using jquery
window.onload = function(){
var anchors = document.getElementById('link_other').getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
anchors[i].setAttribute('target', '_blank');
}
}
// jquery is prettier. :-)
また、タイトルタグを追加して、これを実行していることをユーザーに通知し、警告することができます。
$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');
他のヒント
非jquery:
// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');
// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');
for(var i in linkList){
linkList[i].setAttribute('target', '_blank');
}
これを行うことは、一般にWeb開発者とユーザビリティの専門家によって悪い習慣と見なされていることに注意してください。 Jakob Nielsonは、ユーザーのブラウジングエクスペリエンスの制御を削除することについて次のように述べています。
可能な限り複数のブラウザウィンドウを生成しないようにします&#8212; 「戻る」ボタンをユーザーから離すと、ユーザーのエクスペリエンスが非常に苦痛になり、通常、提供しようとしているメリットをはるかに上回ります。 2番目のウィンドウを作成することを支持する一般的な理論の1つは、ユーザーがサイトを離れないようにすることです。
これが、XHTML 1.1仕様からW3Cによって削除されるターゲット属性の理論的根拠だと思います。
このアプローチをとるのが難しい場合は、Pim Jagerのソリューションが適しています。
より良い、よりユーザーフレンドリーなアイデアは、すべての外部リンクにグラフィックを追加し、リンクをたどると外部に移動することをユーザーに示すことです。
jqueryでこれを行うことができます:
$('a[href^="http://"]').each(function() {
$('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)
});
jQueryの使用:
$('#link_other a').each(function(){
$(this).attr('target', '_BLANK');
});
すべての外部リンクにこれを使用します:
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
if (anchors[i].hostname != window.location.hostname) {
anchors[i].setAttribute('target', '_blank');
}
}
}
インライン:
$('#link_other').find('a').attr('target','_blank');
すべての外部リンクにこれを使用します
$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');
所属していません StackOverflow