简体   繁体   中英

How to trigger "ready" only once in JQuery?

My way like below does not work. Is there other way to trigger ready event only once? Thanks

$("#id").one("ready", function (){
// do somthing
});

I really recommend you read the jQuery documentation because I'm sure that you will find other way to solve your issue. document ready is not for this purpose.

http://learn.jquery.com/using-jquery-core/document-ready/

If you want to do something with #id when the document is ready , here is what you have to do:

$(function() {
    // do something
    $('#id').css('background', 'red);

    // do other things
});

There should be only one ready function in your code and it should brace all you jQuery code.

As said above, read the documentation, you won't lose your time.

I will summarize those concepts:

The js file must have just one $( document ).ready() function, because this function is only for make sure that the code inside it will only run after the "document is ready" (Document Object Model (DOM) is ready for JavaScript code to execute - jQuery documentation). It means that, once all of the HTML as loaded, then your js wil run.

Ok, after know that you can write your focus function inside the document ready to make sure it will work correctly.

See this example that I did: https://jsfiddle.net/hf60asgo/1/

We have the HTML (DOM):

<input id="inputTest" placeholder="Test"/>
<span id="spanTest">Write something</span>

And the JavaScript (jQuery):

$(document).ready(function(){
    $("#inputTest").focus(function() {
    $("#spanTest").fadeOut(1000);
  });
});

After the document is ready (the input and the span was loaded) the jQuery code will run, but only if you focus (click) in the input.

I hope I could give some light to you.

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