繁体   English   中英

单击按钮时删除行

[英]Remove row when button is clicked

我正在尝试使用Google App脚本中的HtmlService执行此操作。 我研究了它,我无法弄清楚为什么以下不起作用。 https://jsfiddle.net/pfue7b71/

脚本

function removeRow() {
  //  alert("run");
    $(this).closest('tr').remove();
};

HTML

<table>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow()" value="X"></td>
    </tr>
</table>

这是因为函数的上下文。 即在运行的直接代码onClick属性,作品使用对象范围内,因此它具有正确的引用this作为当前对象,但对通话removeRow是在窗口背景下做出的,所以提到this是窗口,而不是物体。 您可以使用当前代码解决这个问题:

function removeRow(object){
    $(object).closest('tr').remove();
};

并将通话更改为:

<table>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
</table>

你去吧: https//jsfiddle.net/pfue7b71/2/

此外,为了将来参考,您应该尝试使用console.log而不是alert ,并使用它来记录重要的事情,例如$(this)

您需要确保this是引用DOM元素,而不是函数。

<table>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
    <tr>
        <td><input type="text"></td>
        <td><input type="text"></td>
        <td><input type="button" onClick="removeRow(this)" value="X"></td>
    </tr>
</table>

您还需要将该函数重命名为removeRow ,因为您在HTML中调用它(在小提琴中不正确)。

function removeRow(e) {
    $(e).closest('tr').remove();
};

https://jsfiddle.net/pfue7b71/3/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM