【发布时间】:2015-09-12 14:41:49
【问题描述】:
我正在做一个小型语言培训项目:
我使用 jQuery.csvToTable 插件从 .csv 文件中导入了德语单词表及其英语翻译。
现在,我想要获得的是,当打开语言按钮时,单元格中的单词将被 HTML 输入替换,并在关闭时恢复。
我想我可以通过 td:nth-child(columnNumber) 的行循环并将所有单词保存到数组中来做到这一点。当第一次单击按钮时,该函数会检查单元格是否有输入 - 如果没有,则添加它,如果有,则将数组恢复到单元格中。
我的问题是,createFirstArr(); 函数没有填充数组,据我所知,问题出在 td:nth-child - 在点击函数之外是看不到的。
您知道我如何从 within document.read() 函数访问 td:nth-child 吗?
因为如果我通过单击调用数组创建函数,它将始终用 <input>-s 填充它,因为它需要实际的单元格内容。
$(document).ready(function() {
//importing from the CSV file
$('#firstTable').CSVToTable('woerterbuch.csv');
//the call for the array creating function
createFirstArr();
//toggle between the words and <input>
$(".toggle").click(function() {
var getID;
var input = "<input>";
if ($(this).attr('id') == 'lang1') {
$(this).toggleClass("selected");
getID = 1;
if ($("td:nth-child(1)").html() != input) {
cellToInput(input, getID);
} else {
inputToCell();
}
}
});
createFirstArr = function() {
// I think the function should be global, not sure about how correct it is tho
firstArr = [];
// looping through the rows
// the problem part, td:nth-child(1) is not seen
$("td:nth-child(1)").each(function() {
var id = $(this).html();
firstArr.push(id);
});
}
cellToInput = function(input, id) {
$("td:nth-child(" + id + ")").each(function() {
$(this).html(input);
});
}
inputToCell = function(id) {
$.each(firstArr, function(i, val) {
$("td:nth-child(" + id + ")").each(function() {
$(this).html(val);
});
});
}
我的最终目标是让用户通过填充空白来检查他的知识,然后检查单元格中的单词是否正确。
提前感谢您的宝贵时间!
【问题讨论】:
-
仅供参考,您不需要使用
.each()。 jQuery修改方法自动修改选择器匹配的所有元素。 -
你的意思是像 $("td:nth-child(1)").html(value) 就足够了吗?一开始我是这样做的,但后来由于某种原因我变成了一个循环。
-
是的,我就是这个意思。
标签: javascript jquery csvtotable