I have some code like this:
if (condition) {
var variable = blah;
}
if (differentcondition) {
var variable = blah;
}
Is this correct?
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
}
});