I'm trying to make an ajax call to grab session data to insert into my page after it's loaded like this
jQuery(function(){ // Add Answer
jQuery(".add_answer").livequery('click',function(){
var count = $(this).attr("alt");
count++;
var count1 = count-1;
$.get('quiz/select', function(p_type){ // Ajax Call for Select Data
$(this).parents('div:first').find('.a_type_'+count1+'').after('' + p_type + '');
$(this).attr("alt", count);
});
});
});
The file i'm calling is found but its contents are not printed out by 'p_type'
and the $(this).attr("alt", count);
part of the function is not executing
Note: I'm using CodeIgniter for my framework and jquery for js
-
I believe your problem has to do with the scope of $(this). Because you've got your ajax get function nested inside your livequery function, inside yet another anonymous function, I'd be willing to bet that $(this) is now refering to your $.get() call or something.
You need to cache $(this) as soon as possible at the point where you know it has the correct object selected:
jQuery(".add_answer").livequery('click',function() { var add_answer = $(this); $.get(...) { add_answer.parents('div:first')... } }
The above code should cache the add_answer element, but my livequery knowledge is a bit rusty.
Some recommendations on your code:
- Be consistent with the use of either jQuery() or $() shortcuts, they do the same thing.
- What's with the anonymous function surrounding the whole snippet? Is that just for a simplified example? It should probably be replaced with a $(document).ready(function { ... });
Kevin Gorski : Using $(function() { ... }) is equivalent to $(document).ready(function { ... });Soviut : you're right. I've always found $(document).ready() to be clearer in its intentions. -
"this" is a special keyword in Javascript. In your outer function it refers to .add_answer element. And in your inner function it refers to window.
jQuery(".add_answer").livequery('click',function(){ var self = this; // ... $.get('quiz/select', function(p_type){ // ... $(self).attr("alt", count);
0 comments:
Post a Comment