gpt4 book ai didi

javascript - Jquery 将新数据附加到旧数据有重复问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:09:07 25 4
gpt4 key购买 nike

如何在不复制表格的情况下向旧数据添加新数据?

逻辑

  1. 我选择选项,数据返回表
  2. 我选择不同的选项,数据添加到旧的

问题

当我执行逻辑的第二部分时,它也会添加新表,意味着根据我更改所选选项的次数,它会添加新表。

截图

当我选择我的第一个选项时有一个表

one

当我选择第二个选项时有 2 个表

two

我想要什么

我想要的是当我选择我的第二个/第三个选项 image 2 时,只有 1 表包含所有那些过去和当前选项的数据,而不是为他们每人制作一张 table 。

代码

HTML

<div class="mt-20 options"></div>

JavaScript

<script>
$(function(){
$('select[name="options"]').on('change', function() {
var addressID = $(this).val();
if(addressID) {
$.ajax({
url: '{{ url('admin/getoptions') }}/'+encodeURI(addressID),
type: "GET",
dataType: "json",
success:function(data) {
// $('div.options').empty();

$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th width="50" class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');

// 2. Loop through all entries
var keys = ['title'];
data.forEach(function(row) {
var $row = $('<tr />');

$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row['id']+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');

$('#table tbody').append($row);
});
}
});
}else{
$('div.options').empty();
}
});
});
</script>

有什么想法吗?

最佳答案

以下是要采取的步骤:

  1. 删除 $('div.options').append( ... ) 调用
  2. 将以下 HTML 添加到您的静态 div 元素,并使用 style="display:none" 隐藏它:

    <div class="mt-20 options" style="display:none">
    <div class="mb-20"><h4>Check mark your needed options only</h4></div>
    <table id="table" class="table table-bordered table-hover table-responsive">
    <thead>
    <th width="50" class="text-center">Check</th>
    <th class="text-center">Title</th>
    <th class="text-center">Price</th>
    </thead>
    <tbody>
    </tbody>
    </table>
    </div>
  3. data.forEach 循环之后添加代码,以取消隐藏 div:

        $('#table tbody').append($row);
    }); // end of loop
    $("div.options").show(); // <---

关于javascript - Jquery 将新数据附加到旧数据有重复问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54159627/

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