将favicon附加到班级名称

时间:2012-03-20 11:31:01

标签: javascript jquery url favicon

我有这个脚本:JsBin

它允许将相应的favicon显示到某个URL。正如您所看到的那样,favicon被附加到网址上,但是我需要它附加到class="class"我该怎么做?我没有在代码中看到任何可以改变以使其工作的内容。

1 个答案:

答案 0 :(得分:1)

我已修改脚本以包含在" config" var a" target"属性。这个"目标"只不过是一个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>