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("slo开发者_如何学Gow").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 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);
}
});
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
}
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)
Check out this way of organizing your app.js
http://weblogs.asp.net/jaimedelpalacio/archive/2011/03/23/a-way-to-organize-your-javascript-code.aspx
精彩评论