我有一张文档表,每行旁边都有一个复选框。理想情况下,单击复选框会将其添加到单独的div(“收藏夹列表”)中,但是当我取消选中复选框时,它会创建文档html的副本而不是将其删除。看起来好像取消选中该项目并检查它被视为同一事物。不知道为什么。有什么想法吗?
let $table = $("#km-table-id")
let table = $table.DataTable();
let favesArr = [];
function faveFunc(evt) {
// let data = table.row(this.parentNode).data(),
let data = $($(evt.target).prev().find("a")[0]).html(),
checked = $(this).is(":checked"),
dataIndex = favesArr.indexOf(data);
if (checked) {
if (dataIndex === -1) {
favesArr.push(data); // add item
}
} else {
if (dataIndex > -1) {
favesArr.splice(dataIndex, 1); // remove item
}
}
// ($(".populate-faves").empty());
$(".populate-faves").append((data) + '<br/><br/>').addClass("faved-doc")
}; // ------------ faveFunc
$(".checkbox-class").on("click", faveFunc)
$("#add-id").on("click", faveFunc)
更新:
function faveFunc(evt) {
let $table = $("#km-table-id")
let table = $table.DataTable();
let favesArr = [];
let data = $($(evt.target).prev().find("a")[0]).html()
function newList() {
$(".populate-faves").html("");
$("#km-table-id tbody tr").each(function(i, el) {
let fave = $(el).find(".checkbox-class");
let itemText = $(el).find(data);
if($(fave).is(":checked")) { // ------ checked is coming up undefined
$(".populate-faves").append("<li>" + $(itemText).html() + "</li>")
}
});
}
$(".checkbox-class").on("change", newList);
console.log(checked); // true and false working
}; // ------------ faveFunc
$(".checkbox-class").on("click", faveFunc)
$("#add-id").on("click", faveFunc)
答案 0 :(得分:0)
我建议您尝试这种方法。这只是一个示例,您需要对其进行调整以适应您的需求。
$(document).ready(function() {
'use strict';
const updateFavoritesList = () => {
$("#favoritesList").html("");
$("#itemsList tr").each(function(i, el){
const favorite = $(el).find(".favorite-check");
const itemText = $(el).find("td:first-child");
if($(favorite).is(":checked")){
$("#favoritesList").append("<li>" + $(itemText).html() + "</li>")
}
});
}
$(".favorite-check").on("change", updateFavoritesList);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="itemsList">
<tbody>
<tr>
<td>
Item 1
</td>
<td>
<input class="favorite-check" type="checkbox">
</td>
</tr>
<tr>
<td>
Item 2
</td>
<td>
<input class="favorite-check" type="checkbox">
</td>
</tr>
<tr>
<td>
Item 3
</td>
<td>
<input class="favorite-check" type="checkbox">
</td>
</tr>
</tbody>
</table>
<h4>Favorite items</h4>
<ol id="favoritesList" class="favorites-list"></ol>