感谢您在我的这个问题上花费的所有时间。
The Project
我妈妈是一位美术老师,她花费大量时间为她的项目制作剪纸指南。我正在为她开发一种工具,该工具将使她能够通过自己的网站快速构建和共享指南。她的网站是使用wordpress构建的,因此我使用jQuery和jQuery UI构建了该工具。这是实际的样子:
https://i.stack.imgur.com/z3Y5C.gif
UI运行良好,可以继续保存数据,这就是我遇到的麻烦。
问题
我想基于jquery创建的DOM元素创建一个数组。计划是将数组保存到WordPress,然后使用它重建用于查看/编辑的指南。
基本的DOM结构如下:
function saveGuide() {
numberOfSheets = $(".sheet").length;
console.log("number of sheets:", numberOfSheets);
sheetCounter = 1;
for (i = 0; i < numberOfSheets; i++) {
var saveSheets = $(".sheet")
.map(function() {
return {
sheetName: $(this).attr("data-id"),
width: ($(this).width() + 1) / 80,
height: ($(this).height() + 1) / 80,
// Map the pieces in the sheet
pieces: (saveSheets = $(
".sheet[data-sheetnumber='" + sheetCounter + "'] .piece"
)
.map(function() {
return {
pieceName: $(this).attr("data-name"),
pieceColor: $(this).attr("data-color"),
pieceWidth: ($(this).width() + 4) / 80,
pieceHeight: ($(this).height() + 4) / 80,
pieceXPOS: $(this).position().left / 80,
pieceYPOS: $(this).position().top / 80
};
})
.get())
};
})
.get();
sheetCounter++;
}
myJSON = JSON.stringify(saveSheets);
console.log(myJSON);
}
saveGuide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sheet">
<div class="piece"></div>
<div class="piece"></div>
<div class="line"></div>
</div>
<div class="sheet">
<div class="piece"></div>
<div class="piece"></div>
<div class="line"></div>
</div>
因此,每张纸都可以很好地进入数组,但是从最后一张纸开始,每片总是一样的。我猜该变量在每次循环时都会覆盖自身...
这里是保存时数据外观的链接:https://codebeautify.org/jsonviewer/cbff77c4
您可以看到两个工作表列出了相同的部分。
我或者非常接近上班,或者在构建函数的方式上还遥遥无期。但是我感觉我的大脑现在正在融化,可以就需要看的东西使用帮助或建议。
非常感谢。
您可以使用.children([selector])
获取特定元素的子元素。如果设置选择器,将仅返回匹配的子代。
在您的情况下,您应该使用.children([selector])
(或示例中的$(this).children('.piece')
)来获取与每张图纸相关的作品:
$sheet.children('.piece')
function saveGuide() {
return $(".sheet")
.map(function() {
var $sheet = $(this);
return {
sheetName: $sheet.attr("data-id"),
width: ($sheet.width() + 1) / 80,
height: ($sheet.height() + 1) / 80,
// Map the pieces in the sheet
pieces: $sheet.children('.piece')
.map(function() {
var $piece = $(this);
return {
pieceName: $piece.attr("data-name"),
pieceColor: $piece.attr("data-color"),
pieceWidth: ($piece.width() + 4) / 80,
pieceHeight: ($piece.height() + 4) / 80,
pieceXPOS: $piece.position().left / 80,
pieceYPOS: $piece.position().top / 80
};
})
.get()
};
})
.get();
}
var saveSheets = saveGuide();
console.log("number of sheets:", saveSheets.length);
var myJSON = JSON.stringify(saveSheets);
console.log(myJSON);