How to check if object is undefined/null

2019-07-10 03:18发布

问题:

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.

回答1:

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.



回答2:

if(typeof e === 'undefined') {
    // your code here
}