How to check if object is undefined/null

2019-07-10 03:20发布

This question has come up a lot but I can't make it work.

I have 5 divs, I want to hide the div before the last one who was used. So If the user clicks somewhere in div 1, and then clicks somewhere in div 2, div 1 fades out (all of this after an Ajax call)

Here's my code:

$(document).ready(function() {
    $("#[id^='r_form_']").bind("ajax:success", function(evt, data, status, xhr) {
        var $form = $(this);

        $(this).parent().css("background", "green");

        if($lastForm == null) {
            var $lastForm = $(this);
        };

        if(!($lastForm[0] == $form[0])) {
            $lastForm.parent().fadeOut(1500);
            var $lastForm = $(this);
        };
    });
});

If the variable $lastForm is undefined, assign the current form where Ajax happenned.

The variable is always undefined. I added an alert('undefined') in the loop, i always get it. why?

I have a feeling it might be because the variable is reset when the Ajax request comes back. But i'm not really an expert and can't seem to find the answer.

2条回答
【Aperson】
2楼-- · 2019-07-10 03:32

I think it's because it's declared in inner scope. move the declaration to outside of the function. each function create a new scope, so it's not saved to the next call:

Code:

$(document).ready(function() {

    var $lastForm; //<===================
    $("#[id^='r_form_']").bind("ajax:success", function(evt, data, status, xhr) {
        var $form = $(this);

        $(this).parent().css("background", "green");

        if ($lastForm == null) {
            $lastForm = $(this);
        };

        if (!($lastForm[0] == $form[0])) {
            $lastForm.parent().fadeOut(1500);
            $lastForm = $(this);
        };
    });
});​

As commented by @minitech the # in the selector: #[id^='r_form_'] looks like it shouldn't be there.

查看更多
Animai°情兽
3楼-- · 2019-07-10 03:55
if(typeof e === 'undefined') {
    // your code here
}
查看更多
登录 后发表回答