What's wrong with defining JavaScript variables within if blocks?

前端 未结 5 2036
予麋鹿
予麋鹿 2020-12-10 04:31

I have some code like this:

if (condition) {
var variable = blah;
}

if (differentcondition) {
var variable = blah;
}

Is this correct?

5条回答
  •  一个人的身影
    2020-12-10 05:21

    How should I structure this?

    In this case, it looks like it would be better to nest the conditions:

    $("#container").click(function (event) {
        if ($(event.target).is('img')) {
            var imagesrc = $(event.target).attr('src');
    
            if ($(event.target).is('.class1')) {
                // Do something with imagesrc
            }
    
            if ($(event.target).is('.class2')) {
                // Do something with imagesrc
            }
    
            // This condition is mutually exclusive to the above 2
            if ($(event.target).is('.class3')) {
                // Do something with imagesrc
            }
    
            // This condition is mutually exclusive to 1 and 2 but not to 3
            if ($(event.target).is('.class4')) {
                // Do something with imagesrc
            }
        }
    });
    

    Or better yet use jQuery's event delegation:

    $("#container").on("click", "img", function (event) {
        var imagesrc = $(this).attr('src');
    
        if ($(this).is('.class1')) {
            // Do something with imagesrc
        }
    
        if ($(this).is('.class2')) {
            // Do something with imagesrc
        }
    
        // This condition is mutually exclusive to the above 2
        if ($(this).is('.class3')) {
            // Do something with imagesrc
        }
    
        // This condition is mutually exclusive to 1 and 2 but not to 3
        if ($(this).is('img.class4')) {
            // Do something with imagesrc
        }
    });
    

提交回复
热议问题