简体   繁体   English

如何将jquery链接到外部js文件?

[英]How to link jquery to an external js file?

I´m trying to link jquery to an external js file, but I can´t get it to work. 我正在尝试将jquery链接到外部js文件,但无法正常工作。 This is my full html. 这是我的完整html。 I have put jquery before the js file, as you can see. 如您所见,我将jQuery放在js文件之前。 I also tryed to link both the jquery and js in the body after the div, but that didn't work either. 我也尝试在div之后将主体中的jquery和js都链接起来,但是那也不起作用。

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css-teachers/lessons- teacher.css"/>
<script src="../jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../javascript-teachers/lessons-teacher.js"></script>

 <meta charset="UTF-8">

 <title>HOME</title>
 </head>
 <body>

 <div id="box1"> <a href="page2.html"/></div>
 <div id="box2"> <a href="page3.html"/></div>
 <div id="box3"> <a href="#"/></div>
 <div id="box4"> <a href="#"/></div>
 <div id="box5"> <a href="#"/></div>
 <div id="box6"> <a href="#"/></div>

 </body>
 </html>

My js works if I put it into the body like this 如果我像这样将其放入体内,我的js就可以正常工作

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css-teachers/lessons- teacher.css"/>

 <meta charset="UTF-8">

 <title>HOME</title>
 </head>
 <body>

 <div id="box1"> <a href="page2.html"/></div>
 <div id="box2"> <a href="page3.html"/></div>
 <div id="box3"> <a href="#"/></div>
 <div id="box4"> <a href="#"/></div>
 <div id="box5"> <a href="#"/></div>
 <div id="box6"> <a href="#"/></div>

<script src="../jquery-1.11.3.min.js"></script>
<script> 
$("#box1").click(function() {
window.location = $(this).find("a").attr("href"); 
return false;
}); 

</script>
</body>
</html>

Any suggestions on what I should do? 关于我应该做什么的建议?

Thanks in advance 提前致谢

if you link your script inside the tag <head> </head> maybe you have to include the type: 如果将脚本链接到标签<head> </head>可能必须包括以下类型:

<script type="text/javascript" src="../jquery-1.11.3.min.js"> </script>

like the same way you did with your home.js 就像处理home.js一样

Glad my comment above helped. 很高兴以上我的评论有所帮助。

Just wanted to mention that, since you're using jQuery, you can also put the code in your external file in the following code block to prevent it from executing until all page elements are rendered: 只是想提一下,由于您使用的是jQuery,因此您还可以将代码放在下面的代码块中的外部文件中,以防止它在呈现所有页面元素之前执行:

$(document).ready(function() {
    $("#box1").click(function() {
        window.location = $(this).find("a").attr("href"); 
        return false;
    }); 
});

More info: https://learn.jquery.com/using-jquery-core/document-ready/ 更多信息: https : //learn.jquery.com/using-jquery-core/document-ready/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM