Here is my jQuery:
jQuery( document ).ready( function ( $ ) {
$('ul li:first-child').addClass( 'first_item' );
var className = $('.first_item').attr('id');
alert('Date is:'+ className +'.');
});
And then this another section of jQuery, that im trying to contrust a variable in:
j(".refreshMe").everyTime(5000, function (i) {
j.ajax({
url: "test.php?latest=" + className + "",
cache: false,
success: function (html) {
j(".refreshMe").html(html);
}
Its this line:
url: "test.php?latest="+className+"",
Im trying to 开发者_运维技巧take the className variable and feed it into this line.
Can anyone suggest what im doing wrong here?
Looks to me that the problem is simply the fact that you declared "className" inside that "ready" handler, so it's not visible to the other code.
Pull the declaration out of there and make it global (though see below):
var className;
Then remove var
on the line in the "ready" handler
className = $('.first_item').attr('id');
Now, global variables like that certainly work, but it's kind-of ugly. It might be nicer if you just moved that "everyTime" thing inside the same "ready" handler and keep the variable local.
declare the var classname outside of either function, and it will have the proper scope to do what you're attempting.
Try removing the var
keyword from the variable to make it available publically:
className = $('.first_item').attr('id');
Or you might want to declare this variable outside of the ready handler just below the <script>
tag:
var className = null;
The problem is with the scope of the variable className. Declare it outside (above) the document.ready() function so that the score of className extends to the whole of the js file
精彩评论