Trying to get this code to work but the error I am getting in firebug is $this is not defined
and I don't understand why
To explain the background about this code I have a list of spans with identical classes so when I click on particular span I need to send an ajax request and update that particular span.
Hopefully that makes sense.
$(document).ready(function() {
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($this, 'featured'); });
$('.visible-value').click(function() { return postAndFade($this, 'visible'); });
});
on if not a function" jQuery error occurs for 2 main reasons: Loading an old version of the jQuery library that doesn't support the on function. Loading a library that overrides the value of the dollar sign $ variable.
$(this) is a jQuery object that is wrapping the DOM element this and jQuery objects don't have id properties. You probably want just this.id to get the id attribute of the clicked element.
not defined: In JavaScript, it is one of the reference errors that JavaScript will throw when someone accesses the variable which is not inside the memory heap.
Because it's not - you're looking for $(this)
.
Fuller explanation - jQuery sets the context of event handlers by setting the value of this
to the element triggering the event. In order to reference this in jQuery, you need to wrap it in a jQuery call, like this: $(this)
. Because you often need to do lots of stuff with that element, it's a common coding pattern to assign it to a variable called $this
:
$(el).click(function() {
var $this = $(this);
// now do stuff with $this
});
But that's a convention, not something jQuery does for you.
use this code
$(this) instead of $this
You want $(this)
, not $this
.
You want
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
this
is a reference to the DOM element.
$this
isn't anything, it is sometimes used like so: var $this = $(this)
in order to save the jQuery object, so you aren't recreating it multiple times.
Try to use $(this) instead of $this
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With