【问题标题】:jQuery: td:nth-child can't be called from document.readyjQuery: td:nth-child 不能从 document.ready 调用
【发布时间】: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


【解决方案1】:

CSVToTable 使用 AJAX 加载 CSV 文件,因此这是异步完成的。您正在尝试在加载之前访问该表。 CSVToTable 完成加载表时触发loadComplete 事件,您需要在此事件处理程序中运行您的函数。

$('#firstTable').CSVToTable('woerterbuch.csv').on("loadComplete", createFirstArr);

【讨论】:

  • 好的,这回答了我的问题。谢谢!关于是否可以将此数组保留为全局或不正确/安全的任何迹象?
  • 一般来说,全局变量是个坏主意,因为它们可能会在不同的应用程序之间发生冲突。您可以将所有函数放在 document.ready 函数中,并将变量设为本地变量。
  • 我明白了,到时会这样做。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-30
  • 2011-12-10
  • 2016-10-29
相关资源
最近更新 更多