简体   繁体   English

如何在HTML文件中集成没有任何代码的jQuery代码

[英]How to integrate jquery code without any code in the html file

I want to clear my code a little bit and I want to run my jquery code without any function call in the html file. 我想一点点清除代码,并且我想运行jQuery代码而不在html文件中调用任何函数。 My actual code is : 我的实际代码是:

HTML: HTML:

<head>
    <script src="js/colorpick.js"></script>   
    <script>
        $(document).ready(function() {
            colorpick_start();
        });
    </script>
</head>

JS: JS:

function colorpick_start() {
...
    }

But if I write for example an alert in the first row of the js without any function call, that works. 但是,例如,如果我在js的第一行中编写了一个警报,而没有任何函数调用,那将起作用。

alert('test');

    function colorpick_start() {
    ...
        }

But this is not working for jquery selectors or something. 但这不适用于jQuery选择器或其他东西。 Is there any solution to get my jquery working without code in the html file? 有什么解决方案可以使我的jquery在html文件中不带代码的情况下工作?

I want my html file to look like this, if this is possible: 我希望我的html文件看起来像这样,如果可能的话:

<head>
    <script src="js/colorpick.js"></script>   
</head>

The

$(document).ready(function() {

Waits until the DOM is ready for selectors etc. 等待直到DOM准备好进行选择器等。

If you add the 如果您添加

$(document).ready(function() {

to your colorpick.js file it will wait for the DOM to be ready and then execute colorpick_start(). 到您的colorpick.js文件,它将等待DOM准备就绪,然后执行colorpick_start()。

And believe me this catches out most people when they start using JQuery. 并且相信我,这在大多数人开始使用JQuery时会吸引他们。

Put your script 放你的剧本

<script src="js/colorpick.js"></script> 

before </body> tag. </body>标记之前。 This will ensure that your page is loaded fully before script starts. 这将确保在脚本启动之前完全加载页面。

 $(document).ready(function() {
        colorpick_start();
    });

this code is working because you are calling your function after document is loaded. 该代码有效,因为在文档加载后正在调用函数。 document load is event. 文档加载是事件。 you can put your function on any event you want, but it wont start if you just define your function. 您可以将函数放在所需的任何事件上,但是如果您仅定义函数,它将不会开始。 You have to somehow call your function. 您必须以某种方式调用您的函数。 example would be on click (or on document load) 例如单击(或加载文档)

  <div id="example"></div>


  $("#example").on('click', function () {

    your function here

    });

In order to achieve this: 为了实现这一点:

<head>
   <script src="js/colorpick.js"></script>   
</head>

Move the document ready call to the js file you are referencing in your HTML file and make sure that the method called is present. 将文档就绪调用移至HTML文件中正在引用的js文件,并确保存在被调用的方法。

$(document).ready(function() {
        colorpick_start();
});

This should so it. 应该这样。

Use that code: 使用该代码:

$(function(){
  $('.colorpicker').val("colorpicker"); //or whatever you like
 });

Plnkr example code plnkr示例代码

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

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