简体   繁体   中英

ready function triggers in every page

I have a rails app, if the user is not logged in, I am redirecting to a page, which has one br tag with a class. Like this

<br class="logged">

In the Javascript on ready of that function, I am triggering a modal as follows.

$(document).ready(function(){

 $('.logged').ready(function(){
    $('#open-login').click();
 });

});

This is working fine, except this modal is getting triggered on every page of the app. I mean that br tag is there in only page of the app, how it is ready for every page is what I don't understand. If anyone can tell what went wrong with my approach, it would be of great help.

ps: It's rails application

You can try this:

$(document).ready(function(){

if ($('.logged').length > 0)
    $('#open-login').click();
 }

});

Into if condition you can declare an element of specific page and in only that page you can execute an action.

The jQuery .ready() method can only be called on a jQuery object matching the current document. Attaching it to a $('.logged') selector still makes its handler function get called when the document is ready - it doesn't care about the selector.

MarcoSantino's answer will work for your needs, although you may find it cleaner to add the logged-in class to the body tag instead of inserting a new br tag, and then use the following in your JavaScript:

$(document).ready(function(){
  if ($(body).hasClass('logged-in')) {
    $('#open-login').click();
  }
})

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