英文:
Why does passing "this" from html become undefined?
问题
我有一个HTML按钮。当我将"this"传递给"onclick"函数时,它说元素是"undefined"。
我有一个HTML表格,每一行都有一个删除按钮。当单击它时,我想删除该行。
控制器:
deleteRow(btn) {
let row = btn.parentNode.parentNode; //这应该是<tr>行元素
let name = row.getElementsByTagName("TD")[0].innerHTML;
let table = document.getElementById("nutrient-table");
table.deleteRow(row.rowIndex);
};
模板:
<tr>
<td>维生素C</td>
<td class="dv"></td>
<td class="dv">2%</td>
<td>
<button class="fa fa-minus" (click)="deleteRow(this)"></button>
</td>
</tr>
错误信息显示
btn.parentNode is undefined
我看到另一个地方出现"btn is undefined"的消息。
有什么建议吗?
英文:
I have an html button. When I pass "this" in the "onclick" to a function, it says it's the element is "undefined".
I have an html table with a delete button in each row. I want to delete the row when it is clicked.
Controller:
deleteRow(btn) {
let row = btn.parentNode.parentNode; //this should be the <tr> row element
let name = row.getElementsByTagName("TD")[0].innerHTML;
let table = document.getElementById("nutrient-table");
table.deleteRow(row.rowIndex);
};
Template:
<tr>
<td>Vitamin C</td>
<td class="dv"></td>
<td class="dv">2%</td>
<td>
<button class="fa fa-minus" (click)="deleteRow(this)"></button>
</td>
</tr>
The error message says
> btn.parentNode is undefined
Another place I saw "btn is undefined"
Any ideas?
答案1
得分: 1
From Angular documentation, you should be able to access the button element from within the event handler code in HTML as $event.currentTarget
, given that for native DOM elements, $event
is a DOM event object. Hence you could try
<button class="fa fa-minus" (click)="deleteRow($event)">Delete Row</button>
and have the handler work out the row from the event object.
Please note I am not an Angular programmer and this approach, if it works, may be anathema to Angular-philes for all I know.
英文:
From Angular documentation, you should be able to access the button element from within the event handler code in HTML as $event.currentTarget
, given that for native DOM elements, $event
is a DOM event object. Hence you could try
<button class="fa fa-minus" (click)="deleteRow($event)">Delete Row</button>
and have the handler work out the row from the event object.
Please note I am not an Angular programmer and this approach, if it works, may be anathema to Angular-philes for all I know.
答案2
得分: 1
以下是翻译好的部分:
<tr *ngFor="let row of rows">
<td>Vitamin C</td>
<td class="dv"></td>
<td class="dv">2%</td>
<td>
<button class="fa fa-minus" (click)="deleteRow(row)"></button>
</td>
</tr>
英文:
since you are using angular, this should be much simpler than you are making it. it should probably look something more like this:
<tr *ngFor="let row of rows">
<td>Vitamin C</td>
<td class="dv"></td>
<td class="dv">2%</td>
<td>
<button class="fa fa-minus" (click)="deleteRow(row)"></button>
</td>
</tr>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论