gpt4 book ai didi

javascript - div 只追加一次

转载 作者:行者123 更新时间:2023-12-02 14:01:49 24 4
gpt4 key购买 nike

我有以下代码:

    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;

}

它成功了,它创建了元素并将其 append 到 DOM。

我想清理它,所以我尝试了这个:

    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);
});

但是,我注意到它只 append 循环中的最后一个数组项。这是因为每次都必须重新创建变量吗?或者因为它在 append 之前将所有内容添加到 Accordion 选项中?或者覆盖相同的变量?

我的最终解决方案:

<小时/>
    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);
});

最佳答案

简单的内联怎么样,因为唯一的区别是日期中的数组。

$.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);
});
});

关于javascript - div 只追加一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40363321/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com