脚本的位置在Jquery中是否重要? [英] Does the location of script matter in Jquery?

查看:80
本文介绍了脚本的位置在Jquery中是否重要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我在使用JQuery时脚本标签的位置是否重要吗?

Could someone tell me if the location of the script tag matters while using JQuery?

例如:

<script>
 $("a").click(function(event) {
   event.preventDefault();
   $('<div/>')
      .append('default ' + event.type + ' prevented')
      .appendTo('#log');
 });
</script>

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>

上述代码无法正常工作,但以下工作正常,

The above code does not work as needed but the following works,

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>
<script>
$("a").click(function(event) {
   event.preventDefault();
   $('<div/>')
      .append('default ' + event.type + ' prevented')
      .appendTo('#log');
});
</script>

为什么第二个有效?是因为代码是从上到下连续工作的吗?此外,如果第一个代码在 .ready()内,那么位置无关紧要。

Why did the second one work? Is it because the code is working serially, top to bottom? Also, if the first code is inside .ready(), then the position does not matter.

推荐答案

这个位置很重要。在第一种情况下,您将脚本放在DOM元素之前,这意味着您需要将其包装在 <$ c $中c> document.ready 处理程序,否则当您附加 .click 处理程序时,锚点尚不存在。以下是如何将脚本包装到文档中,这意味着只有在加载完整DOM并准备好操作时才会附加.click处理程序:

The location does matter. In the first case you are placing the script before the DOM element meaning that you need to wrap it in a document.ready handler otherwise at the moment you are attaching the .click handler the anchor doesn't yet exist. Here's how you could wrap the script into a document ready meaning that the .click handler will be attached only when the full DOM is loaded and ready to be manipulated:

<script>
$(function() {
    $("a").click(function(event) {
        event.preventDefault();
        $('<div/>')
            .append('default ' + event.type + ' prevented')
            .appendTo('#log');
    });
});
</script>

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>

将脚本放在文档的末尾(就在结束<之前) ; body> tag)也是一个很好的做法(实际上它是 加速网站的最佳实践 )在这种情况下,您无需将其包装在 document.ready

Placing the script at the end of the document (just before the closing <body> tag) is also a good practice (actually it is one of the recommendations of Best Practices for Speeding Up Your Web Site) and in this case you don't need to wrap it in a document.ready.

这篇关于脚本的位置在Jquery中是否重要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆