문제

다음 코드가 있다고 가정 해 봅시다.

<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가 추가됩니다 target="_blank" div 내의 모든 링크에 link_other.

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');
}

이 작업을 수행하는 것은 웹 개발자와 유용성 전문가가 일반적으로 나쁜 관행으로 간주됩니다. Jakob Nielson은 사용자 브라우징 경험의 통제 제거에 대해 다음과 같이 말합니다.

가능한 경우 여러 브라우저 창을 때리는 것을 피하십시오. 사용자로부터 "뒤로"버튼을 가져 가면 경험이 너무 고통스러워서 일반적으로 제공하려는 모든 이점보다 훨씬 더 중요합니다. 두 번째 창을 때리는 데 유리한 일반적인 이론 중 하나는 사용자가 사이트를 떠나지 못하게하지만 아이러니하게도 원하는 경우 돌아 오는 것을 방지함으로써 반대 효과가있을 수 있습니다.

이것이 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');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top