【问题标题】:Using context and "this" in jQuery在 jQuery 中使用上下文和“this”
【发布时间】:2011-07-28 19:43:06
【问题描述】:

我正在处理一个项目,该项目要求我在单击另一个表中的等效行时使表中的单元格可编辑。我遇到的问题是我不能让它只使可更新表中的单行可编辑,而是使每一行的每个单元格都可编辑。

这是 jsfiddle 上的一个示例,演示了该问题:http://jsfiddle.net/z9qtH/24/

在此示例中,如果您单击顶部表格中的“第 1 行”,则下表的第一行应将其单元格的内容替换为输入。相反,底部表格中的两行都变得可编辑。

代码

HTML:

<table border="1">
<tr>
    <td class="editable">Row 1</td>
</tr>
<tr>
    <td>Row 2</td>
</tr>
</table>

<table class="updateable" border="1">
    <tr>
        <td>1 - 1</td>
        <td>1 - 2</td>
        <td>1 - 3</td>
    </tr>
    <tr>
        <td>2 - 1</td>
        <td>2 - 2</td>
        <td>2 - 3</td>
    </tr>
</table>

Javascript:

function replaceRowCellContentsWithInput(row) {
    $("td", row).each(function() {
        $(this).html('<input type="text" value="' + $(this).html() + '" />');
    });
}

$(document).ready(function() {
    $("td.editable").click(function() {
        var cell = $(this);
        var rowIndex = cell.parent().index();
        var table = $("table.updateable");

        replaceRowCellContentsWithInput(table.children(rowIndex));
    });
});

【问题讨论】:

  • 实时链接是一个很好的辅助问题,但也总是发布相关代码在问题中。两个原因。 1.人们不应该通过链接来帮助你。 2. StackOverflow 不仅是为您现在提供的资源,也是为将来遇到类似问题的其他人提供的资源。外部链接可以被移动、修改、删除等。通过确保相关代码在问题中,我们确保问题(及其答案)在合理的时间内保持有用。

标签: javascript jquery


【解决方案1】:

您的行:table.children(rowIndex) 选择(可能的thead)和tbody 元素。即使它们没有出现在您的 HTML 中,浏览器也会始终插入 tbody

如果您将其替换为(例如)$('tr', table)[rowIndex],您确定您实际上是在选择表格中的行。

【讨论】:

    【解决方案2】:

    您的问题出在这个特定的选择器上:

    table.children(rowIndex)
    

    Children 返回直接子代——对于&lt;table&gt;,这是&lt;tbody&gt;

    因此,当您将其用作上下文时,您的循环会命中表中的每个 &lt;td&gt;,而不管您单击了哪一行。

    【讨论】:

      【解决方案3】:

      试试 replaceWith()...

      只是根据您的要求进行了修改 .......

       function replaceRowCellContentsWithInput(row) {
              $("td", row).each(function() {
                  $(this).replaceWith('<input type="text" value="' + $(this).html() + '" />');
              });
          }
      

      http://jsfiddle.net/z9qtH/24/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-01
        相关资源
        最近更新 更多