我有一个文档列表,每个文档旁边都有一个复选框。单击复选框应该会将文档附加到单独的div(也称为“收藏夹列表”)。这不起作用,但是单击环绕的div复选框可以正确附加该文档。另一个问题是,当“收藏夹”包含一个或多个文档时,单击复选框将清除列表。
如何正确地将复选框本身注册到click事件而不是复选框周围的div?我尝试了其他方法,例如
$( "input[type='checkbox']" ).on("click", faveFunc)
,但我一直在尝试即将结束,所以我想在这里问一下。
import $ from 'jquery';
var tableRes = '';
export default class {
constructor() {
this.loadTableData();
}
// this area contains code that's irrelevant //
// ------ Rendering checkboxes ------- //
$("#km-table-id tbody tr").on("click", function(evt) {
evt.stopPropagation();
if (evt.target.type !== "checkbox") {
$(":checkbox", this).on("click");
}
});
// ------ Appending checkboxes ------- //
let inputType = $("<input />", {"type": "checkbox"})
let chkboxCol = $("#km-table-id tbody tr > td:nth-child(3)");
chkboxCol.append(inputType).addClass("checkbox-class");
// --- My Favorites functionality ---- //
function faveFunc(evt) {
let anchor = $($(evt.target).prev().find("a")[0]).clone();
// let ancTxt = $(anchor).text();
switch($(".populate-faves").find("a:contains(" + $(anchor).text() + ")").length)
{
case 0:
$(".populate-faves").append(anchor);
break;
default:
$(".populate-faves > a:contains(" + $(anchor).text() + ")").remove();
break;
}
};
function newList() {
let data = $(evt.target).prev().find("a").eq(0).html();
let outputList = $(".populate-faves");
$(".populate-faves").html("");
$("#km-table-id tbody tr)").each(function(i, el) {
let cntxFave = $(".add-id", el);
let fave = $(".checkbox-class", el);
let itemText = $(data, el);
if(cntxFave.is(".add-id")) {
outputList.append("<li>" + itemText.html() + "</li>");
}
if(fave.prop("checked")) {
outputList.append("<li>" + itemText.html() + "</li>");
}
});
}; // ------------ newList
$(".checkbox-class").on("click", faveFunc);
<div class="col-md-14"> <!-- Right -->
<table id="km-table-id" class="cell-border display stripe-hover">
<thead>
<tr>
<!-- <th></th> -->
<th></th>
<th></th>
<th>Title</th>
<th></th> <!-- Keep here--this is for checkbox col -->
</tr>
</thead>
<tbody></tbody>
</table>
import $ from 'jquery';
import dt from 'datatables.net';
var categories = '';
var tableRes = '';
export default class {
constructor() {
this.loadCategoryData();
this.loadTableData();
}
let KMdocs = {
{
"d": {
"results": [
{
"__metadata": {
"id": "[redacted]",
"uri": "[redacted]",
"etag": "\"2\"",
"type": "[redacted]"
},
"File": {
"__metadata": {
"id": "[redacted]",
"uri": "[redacted]",
"type": "SP.File"
},
"Name": "Guide to Product IDs.docx"
},
"FileLeafRef": "Guide to Product IDs.docx",
"ResourceType": {
"__metadata": {
"type": "Collection(SP.Taxonomy.TaxonomyFieldValue)"
},
"results": [
{
"Label": "Guides \uff06 Protocols",
"TermGuid": "[redacted]",
"WssId": 706
}
]
},
"EncodedAbsUrl": "[redacted]"
},
{
"__metadata": {
"id": "[redacted]",
"uri": "[redacted]",
"etag": "\"3\"",
"type": "SP.Data.KMDocumentsItem"
},
"File": {
"__metadata": {
"id": "[redacted]",
"uri": "[redacted]",
"type": "SP.File"
},
"Name": "LRRP Template 1.docx"
},
"FileLeafRef": "LRRP Template 1.docx",
"ResourceType": {
"__metadata": {
"type": "Collection(SP.Taxonomy.TaxonomyFieldValue)"
},
"results": [
{
"Label": "Templates",
"TermGuid": "[redacted]",
"WssId": 941
},
{
"Label": "Guides \uff06 Protocols",
"TermGuid": "[redacted]",
"WssId": 706
}
]
},
"EncodedAbsUrl": "[redacted]"
},
{
"__metadata": {
"[redacted]",
"uri": "[redacted]",
"etag": "\"3\"",
"type": "SP.Data.KMDocumentsItem"
},
"File": {
"__metadata": {
"id": "[redacted]",
"uri": "[redacted]",
"type": "SP.File"
},
"Name": "LRRP Template 2.docx"
},
"FileLeafRef": "LRRP Template 2.docx",
"ResourceType": {
"__metadata": {
"type": "Collection(SP.Taxonomy.TaxonomyFieldValue)"
},
"results": [
{
"Label": "Templates",
"TermGuid": "[redacted]",
"WssId": 941
},
{
"Label": "Guides \uff06 Protocols",
"TermGuid": "[redacted]",
"WssId": 706
}
]
},
"EncodedAbsUrl": "[redacted]"
}
]
}
}
}
// ------ Loading Category data ------ //
loadCategoryData() {
let res = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"FileName": obj.FileLeafRef,
"Titles": obj.File.Name,
"Path": obj.EncodedAbsUrl,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";")
};
});
let label = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return obj.ResourceType.results.map(function(val) {
return val.Label;
})
});
// ---------- Unique Categs. --------- //
let unique = [];
let temp = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).forEach(function(obj) {
obj.ResourceType.results.forEach(function(val) {
let divCat = document.createElement("div");
$(divCat).attr("category", encodeURIComponent(val.Label));
$(divCat).html(val.Label);
if (!unique.includes(divCat.outerHTML)) {
unique.push(divCat.outerHTML); // value can be anything, only keys matter
}
})
});
let categories = unique.sort();
$(".indiv-label").append(categories);
} // ------------- loadCategoryData()
// ------ Loading doc title data ----- //
loadTableData() {
// Local icons exist under /SiteAssets/images, if needed //
function docType(fileName) {
let docImg = "<img src='[redacted]/Current.ashx/docx.gif' />"
let msgImg = "<img src='[redacted]/Current.ashx/msg.gif' />"
let nrlImg = "<img src='[redacted]/Current.ashx/nrl.gif' />"
let pdfImg = "<img src='[redacted]/Current.ashx/pdf.gif' />"
let pptImg = "<img src='[redacted]/Current.ashx/pptx.gif' />"
let xlsImg = "<img src='[redacted]/Current.ashx/xls.gif' />"
let docStr = fileName.split(".") // .split() seems to be necessary to render the icons
for (var i = 0; i < docStr.length; i++) {
if (docStr[i].includes('doc')) {
return docStr[i] = docImg;
} // -
else if (docStr[i].includes('DOCX')) {
return docStr[i] = docImg;
} // -
else if (docStr[i].includes('rtf')) {
return docStr[i] = docImg;
} // -
else if (docStr[i].includes('msg')) {
return docStr[i] = msgImg;
} //
else if (docStr[i].includes('nrl')) {
return docStr[i] = nrlImg;
} //
else if (docStr[i].includes('pdf')) {
return docStr[i] = pdfImg;
} //
else if (docStr[i].includes('ppt')) {
return docStr[i] = pptImg;
} // -
else if (docStr[i].includes('PPT')) {
return docStr[i] = pptImg;
} // -
else if (docStr[i].includes('potx')) {
return docStr[i] = pptImg;
} // -
else if (docStr[i].includes('xls')) {
return docStr[i] = xlsImg;
} //
}
} // docType
$.noConflict();
let tableRes = KMdocs.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";"),
"Blank": "", // use to create an empty column, if necessary
"docImg": docType(obj.File.Name) // Icon
}
})
// --------- Rendering table --------- //
$('#km-table-id').DataTable({
data: tableRes,
columns: [{
data: "Categories"
}, // available but hidden
{
data: "docImg",
sortable: false
}, // hides sorting arrows in icon col
{
data: "Titles"
},
{
data: "Blank",
sortable: false
}
],
columnDefs: [{
data: "Path",
ordering: true,
targets: [2],
render: function(data, type, row) {
return $('<a>')
.attr({
target: "_blank",
href: row.Path
})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
},
{
searchable: true,
targets: [0],
visible: false
}, // hides Categories col
],
language: {
searchPlaceholder: "Search All Documents"
},
lengthMenu: [10, 25, 50, 100, 250, 500],
order: [],
pageLength: 500, // showing multiple pgs doesn't render all checkboxes...but initially showing all items renders them
paging: true,
pagingType: "full_numbers",
responsive: true,
scrollCollapse: true,
scrollXInner: true,
scrollY: 550,
sDom: '<"top">rt<"bottom"flp><"left">' // affixes dropdown on bottom
});
// ------ Rendering checkboxes ------- //
$("#km-table-id tbody tr").on("click", function(evt) {
evt.stopPropagation();
if (evt.target.type !== "checkbox") {
$(":checkbox", this).on("click");
}
});
// ------ Appending checkboxes ------- //
let inputType = $("<input />", {
"type": "checkbox"
})
let chkboxCol = $("#km-table-id tbody tr > td:nth-child(3)");
chkboxCol.append(inputType).addClass("checkbox-class");
// --- My Favorites functionality ---- //
function faveFunc(evt) {
let anchor = $($(evt.target).prev().find("a")[0]).clone();
switch ($(".populate-faves").find("a:contains(" + $(anchor).text() + ")").length) {
case 0:
$(".populate-faves").append(anchor);
break;
default:
$(".populate-faves > a:contains(" + $(anchor).text() + ")").remove();
break;
}
};
function newList() {
let data = $(evt.target).prev().find("a").eq(0).html();
let outputList = $(".populate-faves");
$(".populate-faves").html("");
$("#km-table-id tbody tr)").each(function(i, el) {
let cntxFave = $(".add-id", el);
let fave = $(".checkbox-class", el);
let itemText = $(data, el);
if (cntxFave.is(".add-id")) {
outputList.append("<li>" + itemText.html() + "</li>");
}
if (fave.prop("checked")) {
outputList.append("<li>" + itemText.html() + "</li>");
}
});
}; // ------------ newList
$(":checkbox").on("click", faveFunc);
$("#add-id").on("click", faveFunc); // does not work
// Linking custom search w/ DT search //
let oTable = $("#km-table-id").DataTable();
$("#searchbar").on("input", function() {
oTable.search($(this)
.val() + " " + decodeURIComponent($(this)
.attr("category"))).draw();
})
} // ------------------ loadTableData
} // ------------- export default class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1, shrink-to-fit=no">
<title>Pages - KM</title>
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.7/css/select.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.5/css/fixedHeader.dataTables.min.css">
<link rel="stylesheet" href="KMStyles.css" type="text/css">
<!-- jQuery first, then Popper.js -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<!------------------------------->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js" defer></script>
<script type="text/javascript" src="https://cdn.datatables.net/select/1.2.7/js/dataTables.select.min.js"></script>
<!------------------------------->
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.6.2/core.min.js"></script>
<script type="text/javascript" src="SiteAssets/scripts/getListItems.js"></script>
</head>
<body>
<script src="./bundle.js"></script>
<div class="km-div-container">
<div class="col-md-3">
<!-- Left -->
<span class="KM-title"><h1>KM</h1></span>
<div class="form-group">
<input category="" class="form-control" daysprior="" id="searchbar" input-all="" placeholder="Search All Documents..." type="search">
</div>
<div id="myFave.hs-gc-header" class="faves-div">
<p style="font-weight:bold">My Favorites:</p>
<div class="populate-faves"></div>
<!-- location of favorited documents -->
</div>
</div>
<!-------------------------------------------->
<div class="col-md-3" id="middle-id">
<!-- Middle -->
<p>
<div class="all-docs-title" category="" style="font-weight:bold; cursor:pointer" input="">All Documents</div>
</p>
<p>
<div class="recently-added-title" category="" days="30" style="cursor:pointer;">Recently Added and/or Modified</div>
</p>
<div id="km-labels">
<a>
<p class="indiv-label" style="cursor:pointer;"></p>
</div>
</div>
<!-------------------------------------------->
<div class="col-md-14">
<!-- Right -->
<table id="km-table-id" class="cell-border display stripe-hover">
<thead>
<tr>
<!-- <th></th> -->
<th></th>
<th></th>
<th>Title</th>
<th></th>
<!-- Keep here--this is for checkbox col -->
</tr>
</thead>
<tbody></tbody>
</table>
<!-- <ul class="custom-menu">
<li data-action="open" id="open-id">Open Document</li>
<li data-action="add" id="add-id">Set As Favorite</li>
<li data-action="email">Email Document</a></li>
</ul> -->
</div>
<!-- col-md-14 -->
<!-- <div class="kmdialog"></div> -->
<!-- what is this? -->
</div>
<!-- km-div-container -->
</body>
</html>
答案 0 :(得分:0)
该演示的核心如下:
event.type
{Event Handler
⇩
$(document).on('change', 'CHECKBOX', addFav);
⇧event.currentTarget
⇧event.target
演示大纲
为每个复选框分配一个具有唯一值的data-*
属性。 例如。data-id="1"
要使用复选框 ex。引用并克隆位于表格单元格前面的表格单元格中的元素:
$(event.target).closest('td').prev('td').find(ANCHOR).clone();
在以下示例中,使用复选框的data-*
属性将其与克隆的元素相关联,将克隆的锚点附加到<li>
, ex。 :
$(LI).addClass('fav'+ID).append(ANCHOR);
未选中此复选框时,该关联用于从收藏夹列表中删除<li>
,例如,例如:
$('.fav'+ID).remove();
以全页模式查看演示
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.css" rel="stylesheet">
<style>
caption {
caption-side: top;
font-size: 1.5rem;
font-weight: 400
}
.favorite {
list-style: none
}
.favorite li::before {
content: '\1f49a\a0\a0'
}
</style>
</head>
<body>
<header class="container">
<section class='row'>
<fieldset class="col-md-12">
<legend>💖 Favorites:</legend>
<ul class='favorite'></ul>
</fieldset>
</section>
</header>
<hr>
<main class='container'>
<section class='row'>
<article class="col-md-12">
<table class='table'>
<caption>Data</caption>
<thead>
<tr>
<th></th>
<th>Link</th>
<th>Title</th>
<th></th>
</tr>
</thead>
<tbody class='table-bordered'>
<tr>
<td></td>
<td>
<a href='#/' class='lnx'>LINK 1: Category I</a></td>
<td>
<label class="custom-control custom-checkbox">
<input class="chx custom-control-input" type="checkbox" data-id='1'>
<b class="custom-control-indicator"></b>
<b class="custom-control-description"> 💙</b>
</label>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<a href='#/' class='lnx'>LINK 2: Category II</a></td>
<td>
<label class="custom-control custom-checkbox">
<input class="chx custom-control-input" type="checkbox" data-id='2'>
<b class="custom-control-indicator"></b>
<b class="custom-control-description"> 💙</b>
</label>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td>
<a href='#/' class='lnx'>LINK 3: Category III</a></td>
<td>
<label class="custom-control custom-checkbox">
<input class="chx custom-control-input" type="checkbox" data-id='3'>
<b class="custom-control-indicator"></b>
<b class="custom-control-description"> 💙</b>
</label>
</td>
<td></td>
</tr>
</tbody>
</table>
</article>
</section>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).on('change', '.chx', addFav);
function addFav(e) {
var tgt = e.target;
var ID = $(tgt).data('id');
if (tgt.checked) {
var lnx = $(tgt).closest('td').prev('td').find('.lnx').clone();
var item = document.createElement('li');
$('.favorite').append(item);
$(item).addClass('fav' + ID).append(lnx);
return false;
} else if (!tgt.checked) {
$('.fav' + ID).remove();
}
}
</script>
</body>
</html>