简体   繁体   中英

Basic JQuery Question

I have the following JQuery code that processes a GET request upon page load:

$(document).ready(function() {  
  var refreshId = setInterval(function()
  {
       $('#tweets').fadeOut("slow").fadeIn("slow");
       $.get("/event", { event:$("input[name=event]").val(), }, function(data) {
         console.log(data.success);
         console.log(data.page_link);
         console.log('Succesfully Loaded Data from JSON FORMAT GET');
         $('#tweets').html(data.html);
         $('#pagelink').html(data.page_link);
       });

  }, 30000); 
});

The problem is I would like this GET request to be processed only on a specific page. My application loads all JQuery files at once, in an application.js file. How can I use JQuery to specify, something other than document ready and what would an ideal selector be?

You could do a conditional based on the existence of an element that only exists on the page you want your code to fire.

Copied from another question:

jQuery.fn.exists = function()
{
    return jQuery(this).length > 0;
}

if ($(selector).exists())
{
    // your code here
}

You could add a class to the body tag.

$(document).ready(function() {  
  if ($('body').hasClass('updateTweets')) {
  var refreshId = setInterval(function()
  {
       $('#tweets').fadeOut("slow").fadeIn("slow");
       $.get("/event", { event:$("input[name=event]").val(), }, function(data) {
         console.log(data.success);
         console.log(data.page_link);
         console.log('Succesfully Loaded Data from JSON FORMAT GET');
         $('#tweets').html(data.html);
         $('#pagelink').html(data.page_link);
       });

  }, 30000); 
  }
});

Couldn't you just include the code on the one page you want it run on?

Somewhere between the <html> tag you can have:

<script type="text/javascript">
[...code...]
</script>

With the code in your question between the <script> tags.

Check the file location with window.location.href then use an ifstatement:

if(window.location.href == 'whatever.html'){
    $(document).ready(function() { 
           ...
    })
}

You can check the location property to find out which page you're in.

You can also check for the existence of an element:

if ($("something").length)

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