簡體   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