将 javascript 保持在外部 - 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10905389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:25:55  来源:igfitidea点击:

Keeping javascript external - doesn't work

javascriptjqueryhtml

提问by anc1revv

When i keep my javascript/jquery external, my code doesn't work. but when i combine them in my html file everything is fine.

当我将 javascript/jquery 保持在外部时,我的代码不起作用。但是当我将它们组合在我的 html 文件中时,一切都很好。

any suggestions as to why this is?

关于为什么会这样的任何建议?

here is the code:

这是代码:

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8" />
       <script type ="text/javascript" src="jquery.js"></script>  
       <script type ="text/javascript" src="program.js"></script>
</head>
<body>
    <div id="clickme">
    Click here
    </div>

    <img id="book" src="book.png" alt="" width="100" height="123" />

    <p>First Paragraph</p>
    <p>Second Paragraph</p>
    <p>Yet one more Paragraph</p>

</body> 
</html>

with external javascript

使用外部 javascript

$('#clickme').click(function() {
  $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});
$("p").click(function () {
     $(this).slideUp();
   });

VERSUS

相对

<!DOCTYPE html>
<html>
<head>
    <script type ="text/javascript" src="jquery.js"></script>  
</head>
<body>

    <div id="clickme">
        Click here
    </div>
    <img id="book" src="book.png" alt="" width="100" height="123" />

    <p>First Paragraph</p>
    <p>Second Paragraph</p>  
    <p>Yet one more Paragraph</p>


    <script>
        $('#clickme').click(function() {
      $('#book').fadeOut('slow', function() {
     // Animation complete.
     });
     });

    $("p").click(function () {
    $(this).slideUp();
     });


    </script>

</body>
</html>

回答by Shyju

I guess you execute the click event before the DOM finishes loading. Wrap your code inside the dom readyevent and it should work, Assuming your path to the external javascript file is correct.

我猜你在 DOM 完成加载之前执行了 click 事件。将您的代码包装在 domready事件中,它应该可以工作,假设您到外部 javascript 文件的路径是正确的。

$(function(){

   $('#clickme').click(function() {
     $('#book').fadeOut('slow', function() {
       // Animation complete.
     });
   });
   $("p").click(function () {
      $(this).slideUp();
   });
});

Always use firebug (console) to see what is wrong with the script, if you run into any script errors.

如果遇到任何脚本错误,请始终使用 firebug(控制台)查看脚本有什么问题。

回答by Oliver

Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...});or moving your external javascript files to the bottom.

您的 javascript 在页面上有元素之前执行。您可以通过使用$(document).ready(function(){...});或将外部 javascript 文件移动到底部来解决此问题。

回答by Zefiryn

Wrap your js code in external file in

将您的 js 代码包装在外部文件中

$(document).ready(function(){

    //your code goes here

});

Right now you are including external js file in header and it is executed. At this point there is no elements so $('#clickme')and $("p")are empty set. In the second example you run this code after rendering html with that elements.

现在,您在标头中包含外部 js 文件并执行它。此时没有元素 so$('#clickme')并且$("p")是空集。在第二个示例中,您在使用该元素呈现 html 后运行此代码。

回答by WickyNilliams

The reason that there is a difference, is that in the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit further...

之所以存在差异,是因为在外部文件中,您的代码在浏览器完全解析 DOM 之前正在执行,因此您试图以编程方式访问浏览器尚不知道的页面元素。这正是大多数人已经说过的,但让我进一步详细说明......

Whilst a lot of people have mentioned using jQuery's document ready handler, I would like to point out that a workable solution is simply to move your script tags to the bottom of the page.

虽然很多人都提到使用 jQuery 的文档就绪处理程序,但我想指出一个可行的解决方案是将脚本标签移动到页面底部。

Not only will this solve your problem in itself, but it will also improve page load times because of how browsers treat scripts. When the browser encounters a script it stops everything else it is doing (known as a "blocking" operation), and parses and executes the script. This causes the page to just appear to stall from a user's perspective, meaning a bad user experience. Thus, because the scripts are parsed and executed only as they are encountered, by moving your scripts to the bottom you allow the browser to fully render the page so that the JavaScript does not block rendering.

这不仅可以解决您的问题本身,而且由于浏览器处理脚本的方式,它还可以改善页面加载时间。当浏览器遇到脚本时,它会停止正在执行的所有其他操作(称为“阻塞”操作),并解析并执行脚本。从用户的角度来看,这会导致页面看起来停滞不前,这意味着糟糕的用户体验。因此,因为脚本仅在遇到它们时才被解析和执行,通过将脚本移到底部,您可以让浏览器完全呈现页面,这样 JavaScript 就不会阻止呈现。

Though rather than justmoving scripts to the bottom of the page, I'd also follow what the others recommended and wrap the whole code in the document ready handler just to be extra safe that your code will always be executed at the correct time.

尽管不是仅仅将脚本移动到页面底部,我还会遵循其他人的建议并将整个代码包装在文档就绪处理程序中,以确保您的代码始终在正确的时间执行。

Also, in the debate of inline or external, external scripts are generally preferred as they are easier to maintain and the browser can cache them independently of the page (providing the correct HTTP headers are present).

此外,在讨论内联或外部脚本时,通常首选外部脚本,因为它们更易于维护,并且浏览器可以独立于页面缓存它们(提供正确的 HTTP 标头)。

To sum up here's some example code:

总结一下这里的一些示例代码:

<html>
<head></head>
<body>
<!-- all your markup here -->

<!-- script at bottom, markup already rendered by this point -->
<script type="text/javascript" src="jquery.js"></script>

<!-- inline or external, still wrap in document ready handler -->
<!-- though external is better because the browser can cache it independently of the page -->
<script type="text/javascript">
    //wrap in document ready to be extra safe
    $(function() { /*code here*/ });
</script>

</html>