简体   繁体   中英

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. My actual code is :

HTML:

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

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.

alert('test');

    function colorpick_start() {
    ...
        }

But this is not working for jquery selectors or something. Is there any solution to get my jquery working without code in the html file?

I want my html file to look like this, if this is possible:

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

The

$(document).ready(function() {

Waits until the DOM is ready for selectors etc.

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().

And believe me this catches out most people when they start using JQuery.

Put your script

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

before </body> tag. 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.

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

This should so it.

Use that code:

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

Plnkr example code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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