开发者

JQuery - $this is not defined

开发者 https://www.devze.com 2023-04-11 13:00 出处:网络
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

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开发者_如何学C('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'); });
});


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'); });
0

精彩评论

暂无评论...
验证码 换一张
取 消