Nice programing

지정된 div 내의 링크에 target =“_ blank”를 어떻게 추가합니까?

nicepro 2020. 12. 2. 21:59
반응형

지정된 div 내의 링크에 target =“_ blank”를 어떻게 추가합니까?


다음 코드가 있다고 가정 해 보겠습니다.

<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>

이 경우 자바 스크립트는 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');
 });

I use this for every external link:

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

Inline:

$('#link_other').find('a').attr('target','_blank');

Use this for every external link

$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');

참고URL : https://stackoverflow.com/questions/804256/how-do-i-add-target-blank-to-a-link-within-a-specified-div

반응형