[英]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();
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.