2010-03-23 44 views
0

我几乎没有任何使用DOM和使用JavaScript的经验,而且我正在努力完成一项非常具体的任务。在网站加载时,如何使用Javascript动态地将所有图片封装在链接中?

比方说,我在我的HTML有一个形象:

<img src="foo.jpg" /> 

当网站负载,我想利用该图像(文档中的所有图像,实际上),并在链接将它们包装:

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

我可以用什么来实现这个目标?关于这个特定的任务,Google对我来说并没有多大的帮助。在加载时,我可以访问和迭代文档中的所有图像......但我不确定该从哪里去,以便将图像包装在链接中。

回答

6

你可以尝试在电线之间的东西:

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

我会用出色的jQuery库操作DOM建议您:

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

+1不知道关于replaceChild,我自己的纯js版本并不知道k很好当我测试它=) – 2010-03-23 08:55:53

0

在下面的例子中,所有的图像成为包裹在一个链接到他们的来源。因此,如果图像的src//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>

相关问题