2012-03-20 24 views
0

我有這樣的腳本:JsBin追加圖標類名

它可以顯示相應的圖標到一定的URL。正如你可以看到的favicon附加到URL,但我需要它追加到class="class"我該怎麼做?我沒有看到代碼中的任何內容,爲了使這項工作我可以改變。

回答

1

我修改了腳本以包含在「config」var「target」屬性中。這個「目標」只不過是一個默認爲「this」的jQuery選擇器(比如.class,在這種情況下)。

所以:

jQuery('#hello').favicons({insert: 'insertBefore', target: '.class' }); //aplies to $('.class') 

    //These 2 are the same 
    jQuery('#hello').favicons({insert: 'insertBefore', target: '#hello' }); //target is the same as "this" 
    jQuery('#hello').favicons({insert: 'insertBefore'}); 

我希望這個作品爲你!

這是一個完整的工作代碼:

<!DOCTYPE html> 
<html> 
<head> 
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
<!--[if IE]> 
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
<![endif]--> 
<style> 
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; } 
</style> 

<script type="text/javascript"> 

    jQuery.fn.favicons = function (conf) { 
     var config = jQuery.extend({ 
      insert:  'appendTo', 
      target:   this 
     }, conf); 

     return this.each(function() { 
      jQuery('a[href^="http://"]', this).each(function() { 
       var link  = jQuery(this); 
       var faviconURL = link.attr('href').replace(/^(http:\/\/[^\/]+).*$/, '$1') + '/favicon.ico'; 

       var faviconIMG = jQuery('<img src="' + '" alt="" />')[config.insert]($(config.target)); 
       var extImg  = new Image(); 

       extImg.src = faviconURL; 

       if (extImg.complete) { 
        faviconIMG.attr('src', faviconURL); 
       } 
       else { 
        extImg.onload = function() { 
         faviconIMG.attr('src', faviconURL); 
        }; 
       } 
      }); 
     }); 
    }; 

    $(function(){ 
     jQuery('#hello').favicons({insert: 'insertBefore', target: '.class' }); 
    }); 

</script> 
</head> 
<body> 
    <p id="hello"><a href="http://www.google.nl/">Google</a></p> 
    <p class="class">apend favicon over her instead</p> 
</body> 
</html> 
+0

太謝謝你了:) – Youss 2012-03-20 13:25:55

+0

也感謝解釋是怎麼回事。 – Youss 2012-03-20 13:26:33

+0

沒問題!快樂的編碼! – fsodano 2012-03-20 15:00:33