开发者

Javascript Jquery doesn't work. $(this)

开发者 https://www.devze.com 2022-12-21 04:12 出处:网络
$(document).ready(function() { $(\".delete_user_button\").click(function(){ var username_to_delete = $(this).attr(\'rel\');
$(document).ready(function() {
    $(".delete_user_button").click(function(){
        var username_to_delete = $(this).attr('rel');
        $.ajax({
开发者_如何学C            type:"POST",
            url:"/delete/",
            data:{'username_to_delete':username_to_delete},
            beforeSend:function() {
                $(this).val("Removing...");
            },
            success:function(html){
                $("div.delete_div[rel=" + username_to_delete + "]").remove();
            }
            });
        return false;
    });
});

Why doesn't $(this).val() work? I'm trying to change the text of the button when the user clicks remove.


In your event handler (beforeSend), this refers to the XMLHttpRequest object used for the ajax call, not your original this of the click event handler. You should "capture" it in a variable first:

$(document).ready(function() {
    $(".delete_user_button").click(function(){
        var element = $(this);
        var username_to_delete = element.attr('rel');
        $.ajax({
            type:"POST",
            url:"/delete/",
            data:{'username_to_delete':username_to_delete},
            beforeSend:function() {
                element.val("Removing...");
            },
            success:function(html){
                $("div.delete_div[rel=" + username_to_delete + "]").remove();
            }
            });
        return false;
    });
});

This mechanism is called "closures". For an interesting explanation of this, check this link:

http://www.bennadel.com/blog/1482-A-Graphical-Explanation-Of-Javascript-Closures-In-A-jQuery-Context.htm


Without more knowledge about the context or analysing the script itself: Keep in mind that, in certain environments, it might be possible that $ itself does not work and needs to be replaced with jQuery - I've seen this in Liferay.

I guess this is not your problem here, but it might come in handy for others looking for this problem from another context.

0

精彩评论

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