2010-03-23 6 views
0

나는 DOM을 사용하여 작업하고 자바 스크립트를 사용하는 경험이 거의 없으며 성취하려는 특정 작업이 있습니다.사이트로드시, 자바 스크립트를 사용하여 동적으로 링크의 모든 이미지를 어떻게 랩핑합니까?

의 내가 내 HTML에 이미지가 있다고 가정 해 봅시다 :

<img src="foo.jpg" /> 

사이트로드, 나는 그 이미지 (실제로 문서의 모든 이미지를) 가지고, 그리고 링크를 포장 할 때 :

<a href="http://www.foobar.com"><img src="foo.jpg" /></a> 

이 작업을 수행하려면 어떻게해야합니까? Google은이 특정 작업과 관련하여 나에게 많은 것을 보여주지 못했습니다. 로드시 문서의 모든 이미지에 액세스하고 반복 할 수 있지만 링크에서 이미지를 래핑하기 위해 어디로 가야할지 잘 모르겠습니다.

window.onload = function() { 
    var images = document.getElementsByTagName('img'); 
    for (var i = 0, image = images[i]; i < images.length; i++) { 
     var wrapper = document.createElement('a'); 
     wrapper.setAttribute('href', 'http://www.foobar.com'); 
     wrapper.appendChild(image.cloneNode(true)); 
     image.parentNode.replaceChild(wrapper, image); 
    } 
}; 

내가 DOM 조작 우수한 jQuery 라이브러리를 사용을 권장합니다 :

답변

6

당신은 선 사이에서 뭔가 시도 할 수있는 다음의 예에서

$(function() { 
    $('img').wrap('<a href="http://foo.com">'); 
}); 
+0

을 +1은 replaceChild에 대해 몰랐고, 내 자신의 일반 js 버전은 wor를하지 않았다. k를 아주 잘 테스트했을 때 =) –

0

을, 모든 이미지에 싸여 될 그들의 출처에 대한 링크. 따라서 이미지의 이 //example.com 인 경우 앵커 (링크)가 //example.com으로 줄 바꿈됩니다. 물론

당신이 데이터과 같이, nolink 속성 추가 할 수 있도록 링크 된 이미지의 일부 싶지 않은 :
<img src="//lorempixel.com/400/200 data-nolink />



<!DOCTYPE html> 
 
<html lang="en-GB"> 
 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!-- Include jQuery 1.11.1 --> 
 

 
    <script> 
 
    $(function() { //Run once DOM is ready 
 
     
 
     $('img:not([data-nolink])').each(function() { //Iterate through each img element 
 
     
 
     $(this).wrap('<a href="' + $(this).attr('src') + '">'); //Wrap with link to own src 
 
     
 
     }); 
 
    
 
    }); 
 
    </script> 
 

 
    <style> 
 
    h3 { 
 
     text-align: justify; 
 
    } 
 
    
 
    img { 
 
     width: 200px; 
 
     margin: 24px; 
 
    } 
 
    </style> 
 
    
 
</head> 
 
<body> 
 

 
    <h3>These images are generated randomly by <a href="lorempixel">loremPixel</a>; So you will be presented by a different image to what you see here, when you click on any of the links </h3> 
 
    <hr /> 
 
    <br /> 
 

 
    <img src="//lorempixel.com/400/200?samp1" /> 
 
    <img src="//lorempixel.com/400/200?samp2" /> 
 
    <img src="//lorempixel.com/400/200?samp3" data-nolink/> <!-- Add data-nolink to prevent auto-linking --> 
 
    <img src="//lorempixel.com/400/200?samp4" /> 
 
    <img src="//lorempixel.com/400/200?samp5" /> 
 
    <img src="//lorempixel.com/400/200?samp6" /> 
 
    
 
</body> 
 
</html>

관련 문제