[英]How do I pass (or reference) “$(this)” from html event?
Let's say I have a button in a table which adds a new row to a table: 假设我在表格中有一个按钮,它会向表格中添加新行:
<td><a onclick="addRow()"></a></td></tr>...
and I want to reference $(this)
or $(this).closest('tr')
from the function at the bottom of the page. 我想从页面底部的函数引用$(this)
或$(this).closest('tr')
。
function addRow(){
$(this) // contains all information from the row which pressed the button
}
Simply passing a javascript variable from the HTML will result in null (as expected). 简单地从HTML传递javascript变量将导致null(如预期)。 Is there a way to reference the row that pressed the button? 有没有办法引用按下按钮的行?
The RECOMMENDED way of doing this is unobtrusive and delegated - give the link a class: 推荐的方式是不引人注意和委托的-给链接一个类:
var $tb = $("#someTable"); $tb.on("click", ".addRow", function(e) { // delegation to allow new rows' links to work e.preventDefault(); // stop any click side effects var $row = $(this).closest("tr"); $tb.append($row.clone()) });
a { text-decoration:none } td,th { padding:3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>A</th> <th>B</th> <th>Add</th> </tr> </thead> <tbody id="someTable"> <tr> <td>1st</td> <td>2nd</td> <td><a class="addRow" href="#">+</a></td> </tr> <tr> <td>3rd</td> <td>4th</td> <td><a class="addRow" href="#">+</a></td> </tr> </tbody> </table>
Use this
用this
<td><a onclick="addRow(this)"></a></td></tr>
and then: 接着:
function addRow(e){ console.log($(e)) // contains all information from the row which pressed the button }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a onclick="addRow(this)">Clickme</a>
You can reference the row that you clicked using an event. 您可以引用使用事件单击的行。
<td><a href="javascript:addRow(this)">Add</a></td>
and in javascript you can check the event 并且可以在javascript中检查事件
<script>
function addRow(event) {
console.log(event);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.