Following instructions below to practise add a link surround image automatic.
Html code before using jQuery
Now, to convert all images included in #main_container block to hyperlink, we use a jQuery function below
Remember add file jQuery library before this function:
==> Result Html code after using jQuery function
Html code before using jQuery
1: <div id="main_container">
2: <ul>
3: <li>
4: <img src="/images/pic_1.jpg" alt="">
5: <div class="description">
6: <p>Some description demo</p>
7: <p>Some description demo</p>
8: </div>
9: </li>
10:
11: <li>
12: <img src="/images/pic_1.jpg" alt="">
13: <div class="description">
14: <p>Some description demo</p>
15: <p>Some description demo</p>
16: </div>
17: </li>
18: <li>
19: <img src="/images/pic_1.jpg" alt="">
20: <div class="description">
21: <p>Some description demo</p>
22: <p>Some description demo</p>
23: </div>
24: </li>
25: <li>
26: <img src="/images/pic_1.jpg" alt="">
27: <div class="description">
28: <p>Some description demo</p>
29: <p>Some description demo</p>
30: </div>
31: </li>
32: </ul>
33: </div>
Now, to convert all images included in #main_container block to hyperlink, we use a jQuery function below
1: $(function(){
2: //Find all images listed in the block #main_container
3: $('#main_container img').each(function ()
4: {
5: //set image founded for a new variable to cache the selector
6: var currImg = $(this);
7: //get the link of image and assign for a link tag around the image
8: currImg.wrap("<a href='" + currImg.attr("src") + "' />");
9: });
10: });
Remember add file jQuery library before this function:
1: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
1: <div id="main_container">
2: <ul>
3: <li>
4: <a href="/images/pic_1.jpg"><img src="/images/pic_1.jpg" alt=""></a>
5: <div class="description">
6: <p>Some description demo</p>
7: <p>Some description demo</p>
8: </div>
9: </li>
10:
11: <li>
12: <a href="/images/pic_2.jpg"><img src="/images/pic_2.jpg" alt=""></a>
13: <div class="description">
14: <p>Some description demo</p>
15: <p>Some description demo</p>
16: </div>
17: </li>
18: <li>
19: <a href="/images/pic_3.jpg"><img src="/images/pic_3.jpg" alt=""></a>
20: <div class="description">
21: <p>Some description demo</p>
22: <p>Some description demo</p>
23: </div>
24: </li>
25: <li>
26: <a href="/images/pic_1.jpg"><img src="/images/pic_1.jpg" alt=""></a>
27: <div class="description">
28: <p>Some description demo</p>
29: <p>Some description demo</p>
30: </div>
31: </li>
32: </ul>
33: </div>
if you want a special image without hyper link you can add a class with a name 'special' or another name you want :)
<img src="/images/pic_1.jpg" alt="" class="special">
and before
currImg.wrap("<a href='" + currImg.attr("src") + "' />");use If..else statements like this
if(currImg.hasClass('special')){//Do nothing}else{ currImg.wrap("<a href='" + currImg.attr("src") + "' />"); }
Categories:
jQuery
0 comments:
Post a Comment