如何将 jQuery 放在一个单独的文件中

how do I put jquery in a separate file?

本文关键字:一个 单独 文件 jQuery      更新时间:2023-09-26

在过去的一个小时左右的时间里,我一直在谷歌上搜索,但似乎无法找到解决这个问题的方法。我刚刚从codecademy完成了jQuery课程,现在正在做一个项目。由于某种原因,我的代码jquery代码将无法正常工作

j查询:

$(document).ready(function(){
$("div").css("border", "3px solid red");
$(".storyblocks").mouseenter(function(){
    $(this).animate({
        height: "+= 20px"
        width: "+= 20px"
    });
});
$(".storyblocks").mouseleave(function(){
    $(this).animate({
        height: "-= 20px"
        width: "-= 20px"
    });
});
}); 

.HTML:

<!DOCTYPE html>
<html>
<head>
<title>Project Website</title>
<link type = "text/css" rel = "stylesheet" href = "stylesheet.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>

我添加了$("div").css("border", "3px solid red");来检查div是否有红色边框,到目前为止还没有运气。有人说我不需要$(document).ready,但我不明白为什么不需要。

请帮忙?

你的jQuery不起作用的问题与将jQuery放在一个单独的文件中无关,它与一个小的语法错误有关:你的animate属性之间没有逗号,并且你的animate属性使用了不正确的语法。

下面是您的代码,但有必要的逗号和用于动画属性的正确语法:

http://jsfiddle.net/4xfAZ/2/

逗号在这里:

$(document).ready(function () {
    $("div").css("border", "3px solid red");
    $(".storyblocks").mouseenter(function () {
        $(this).animate({
            height: ($(this).height() + 20) + 'px',
            width: ($(this).width() + 20) + 'px'
        });
    });
    $(".storyblocks").mouseleave(function () {
        $(this).animate({
            height: ($(this).height() - 20) + 'px',
            width: ($(this).width() - 20) + 'px'
        });
    });
});

在高度声明之后,在下一个声明之前,您需要用逗号分隔。

因为你的jQuery出错了,它没有做任何事情,这就是为什么你没有看到红色边框:)即使红色边框代码与违规代码是分开的。

这将设置边框:

$("div").css("border", "3px solid red"); 

要检查div 是否有 3px 的红色边框:

 if( $("div").css("border") == "3px solid red") {
    console.log('border have red color')
 } 

试试这个:

+=20px不起作用,您需要找到div 的高度,然后添加/减去20px

    $(document).ready(function(){
        $("div").css("border", "3px solid red");
        $(".storyblocks").mouseenter(function(){
            var h = $(this).height()+20;
            var w = $(this).width()+20;
            $(this).animate({
                height: h+"px",//add comma here
                width: w+"px"
            });
        });
        $(".storyblocks").mouseleave(function(){
            var h = $(this).height()-20;
            var w = $(this).width()-20;
            $(this).animate({
                height: h+"px",//add comma here
                width: w+"px"
            });
        });
    });

在这里摆弄。

我想

在另一个js文件中分离我的jquery方法。所以我把Jquery文件像脚本一样放在js文件上并将 src 放在主文件上。

我在 html 文件上写了这段代码

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>

和这段代码在javasciript文件上

$(document).ready(function () {
  $("#some_id").hide(1500);
});

相关文章: