如何从CDN中包含JQuery?

时间:2015-04-24 16:22:59

标签: jquery cdn

我是JQuery的新手,我想知道我是如何引用谷歌的CDN以便让我的JQuery文件工作的。我的脚本没有运行,因为它不会引用JQuery CDN。我在下面尝试做的就是在将鼠标悬停在其上时调整图像大小。它真的不应该太难,但我无法弄清楚如何引用JQuery CDN。任何帮助深表感谢。谢谢!

<!DOCTYPE html>
<html>
<head>
<title>Image Resize</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
var ht = $("img").height(),
    wd = $("img").width(),
    mult = 1.5; 

$("img").on('mouseenter', function () {
    $(this).animate({
        height: ht * mult,
        width: wd * mult
    }, 500);
});
$("img").on('mouseleave', function () {
    $(this).animate({
        height: ht,
        width: wd
    }, 500);
})
</script>

</head>


<body>

<img src="https://cdn1.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/512/social_google_box.png" width="200" height="200" border="5" alt="" style="border-color:red" />

</body>



</html>

3 个答案:

答案 0 :(得分:1)

只需将您的Jquery代码放入这样的块中即可 -

<script>
$( document ).ready(function() {
  // Jquery Code here
});

</script>

您需要执行此操作,因为当您使用$("img").height()之类的代码时,您不希望在浏览器呈现<img>标记之前执行Jquery代码。

您可以在此处详细了解此信息 - http://learn.jquery.com/using-jquery-core/document-ready/

答案 1 :(得分:1)

JQuery已正确包含,但是您要等到文档完全加载后才能调用它。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function() { // this waits until the document is fully loaded
    // Put custom logic here    
});
</script>

此外,您只能在<head>部分中放入CSS include。通常,出于性能原因,JavaScript文件包含在<body>的底部。

答案 2 :(得分:1)

要使jQuery工作,您需要使用$(document).ready()等待文档完全加载,然后再执行jQuery代码。这是正确的代码:

  <!DOCTYPE html>
    <html>
        <head>
            <title>Image Resize</title>
            <script src="https://pagecdn.io/lib/jquery/3.2.1/jquery.min.js"></script>
            <script>
                window.jQuery || document.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"><\/script>');
            </script>

            <script>

            $(document).ready( function() {
                var ht = $("img").height(),
                    wd = $("img").width(),
                    mult = 1.5; 

                $("img").on('mouseenter', function () {
                    $(this).animate({
                        height: ht * mult,
                        width: wd * mult
                    }, 500);
                });

                $("img").on('mouseleave', function () {
                    $(this).animate({
                        height: ht,
                        width: wd
                    }, 500);
                });
            });

            </script>
        </head>
        <body>
            <img src="https://cdn1.iconfinder.com/data/icons/yooicons_set01_socialbookmarks/512/social_google_box.png" width="200" height="200" border="5" alt="" style="border-color:red" />
        </body>
    </html>

在这里,我指定了2个CDN,以确保在您的原籍国Google CDN被阻止的情况下加载jQuery。