Christian4423 Christian4423 - 1 month ago 8
Javascript Question

Div only appends once

I had the following code:

switch (caseType) {
case "dates":
$.each(array.reverse(), function (index, arr) {
var $accordionOption = $('<div />', {
"class": "option",
"data-select": 'option',
"data-action": 'makePie',
text: arr
});

$accordionOption.appendTo($accordionOptionContainer);
$accordionOption.click(function () {
cache.select(this);
});
});
break;
case "cohort":
$.each(array, function (index, arr) {
var $accordionOption = $('<div />', {
"class": "option",
"data-select": 'option',
"data-action": 'makePie',
text: arr
});

$accordionOption.appendTo($accordionOptionContainer);
$accordionOption.click(function () {
cache.select(this);
});
});
break;
case "period":

$.each(array, function (index, arr) {
console.log(arr)
var $accordionOption = $('<div />', {
"class": "option",
"data-select": 'option',
"data-action": 'makePie',
text: arr
});

$accordionOption.appendTo($accordionOptionContainer);
$accordionOption.click(function () {
cache.select(this);
});
});
break;

}


And it worked, it makes the element and appends it to the DOM.

I wanted to clean it up so I tried this:

var $accordionOption = $('<div />', {
"class": "option",
"data-select": 'option',
"data-action": 'makePie'
});

switch (caseType) {
case "dates":
$.each(array.reverse(), function (index, arr) {
$accordionOption.text(arr);
$accordionOption.appendTo($accordionOptionContainer);
});
break;
case "cohort":
$.each(array, function (index, arr) {
$accordionOption.text(arr);
$accordionOption.appendTo($accordionOptionContainer);
});
break;
case "period":

$.each(array, function (index, arr) {
$accordionOption.text(arr);
$accordionOption.appendTo($accordionOptionContainer);
});
break;
}
$accordionOption.click(function () {
cache.select(this);
});


However, I noticed that it only appends the last array item in the loop. Is this because the variable has to be recreated each time? Or because it is adding everything to accordion option before it appends? Or overwriting the same variable?

My final solution:




function getDiv() {
return $('<div />', {
"class": "option",
"data-select": 'option',
"data-action": 'makeTable'
});
}

$.each(caseType == "dates" ? array.reverse() : array, function (index, arr) {
var $accordionOption = getDiv()
.text(arr)
.click(function () { cache.select(this) })
.appendTo($accordionOptionContainer);
});

Answer

how about a simple inline if as the only difference is the array in dates.

$.each(caseType == "dates" ? array.reverse() : array, function(index, arr) {
  var $accordionOption = $('<div />', {
    "class": "option",
    "data-select": 'option',
    "data-action": 'makePie'
  });
  $accordionOption.text(arr);
  $accordionOption.appendTo($accordionOptionContainer);
  $accordionOption.click(function() {
    cache.select(this);
  });
});