我应该把我的 JavaScript 代码放在哪里? [英] Where should I put my JavaScript code?

查看:27
本文介绍了我应该把我的 JavaScript 代码放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自动完成的代码.代码在这里.

<div class="demo"><div class="ui-widget"><label for="tags">标签:</label><输入id=标签">

</div><!-- 演示结束--><div class="demo-description" style="display: none; "><p>当您在字段中输入时,自动完成小部件会提供建议.这里的建议是编程语言的标签,试试ja"(对于 Java 或 JavaScript).</p><p>数据源是一个简单的 JavaScript 数组,使用源选项提供给小部件.</p></div><!-- 演示结束-->

但是,我不知道应该把这段代码放在哪里.在头上?在体内?

解决方案

根据 w3schools

何时将脚本放入 HEAD

<块引用>

脚本执行时调用,或触发事件时,被放置在函数中.把你的函数在 head 部分,这个他们都在一个地方,并且他们不会干扰页面内容.

何时将脚本放入 BODY

<块引用>

如果你不希望你的脚本放在一个函数内,或者如果你脚本应该写页面内容,它应该放在正文部分.

所以在你的情况下.你可以把脚本放在body

I would like to use the code for the auto-complete. The code is here.

<script>
    $(function() {
        var availableTags = [
            "ActionScript",
            "AppleScript",
            "Asp",
            "BASIC",
            "C",
            "C++",
            "Clojure",
            "COBOL",
            "ColdFusion",
            "Erlang",
            "Fortran",
            "Groovy",
            "Haskell",
            "Java",
            "JavaScript",
            "Lisp",
            "Perl",
            "PHP",
            "Python",
            "Ruby",
            "Scala",
            "Scheme"
        ];
        $( "#tags" ).autocomplete({
            source: availableTags
        });
    });
    </script>



<div class="demo">

<div class="ui-widget">
    <label for="tags">Tags: </label>
    <input id="tags">
</div>

</div><!-- End demo -->



<div class="demo-description" style="display: none; ">
<p>The Autocomplete widgets provides suggestions while you type into the field. Here the suggestions are tags for programming languages, give "ja" (for Java or JavaScript) a try.</p>
<p>The datasource is a simple JavaScript array, provided to the widget using the source-option.</p>
</div><!-- End demo-description -->

However, I cannot figure out where I should put this code. In head? In body?

解决方案

According to w3schools

When to put script in HEAD

Scripts to be executed when they are called, or when an event is triggered, are placed in functions. Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

When to put script in BODY

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

So in your case. You can put the script in the body

这篇关于我应该把我的 JavaScript 代码放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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