繁体   English   中英

使用javascript函数获取最近的元素

[英]Getting the closest element using javascript function

 function toDelete(book_id){ var parent = $(this).closest('tr'); $.ajax({ type: 'GET', url: 'url-to-delete-book', data:{ book_id: book_id }, success: function(response){ if(response == 'success'){ parent.slideUp(200,function() { parent.remove(); }); } } }) }; 
 <table> <tbody> <tr> <th>No</th> <th>Title</th> <th>Author</th> <th>Action</th> </tr> <tr> <td>1</td> <td>Harry Potter</td> <td>JK Rowling</td> <td><a href="javascript:;" onclick="toDelete(2)">Delete</a></td> </tr> <tr> <td>2</td> <td>The Great Gatsby</td> <td>F. Scott Fitzgerald</td> <td><a href="javascript:;" onclick="toDelete(1)">Delete</a></td> </tr> </tbody> </table> 

图书数据删除后,我正在尝试删除表格的行。 但是,当我在javascript函数中执行$(this).closest('tr')时,我在控制台中e.fn.init [prevObject: e.fn.init(1), contect: undefined] 如何在函数内部获取父元素? 谢谢。

var parent = $(this).closest('tr');

你传递this jQuery的,但你知道this是在这方面? 如果函数是“刚”之称,像在这种情况下, this将是被称为(函数function toDelete ) -你可以在控制台通过发行记录它console.log(this) 而且该函数没有最接近的<tr>元素。

您应该调用带有该元素的函数以从中选择最接近的<tr>作为this参数(例如toDelete.call(this, 1)从onclick内部选择toDelete.call(this, 1) ),或者将该元素作为参数传递给toDelete函数(例如, toDelete(this, 1) ,而函数定义是function toDelete(element, book_id) ,而jQuery选择器将是$(element).closest('tr')


次要更新

显然,在这种情况下,我并不完全知道this意味着什么。 我在Chrome的开发人员控制台中尝试过, this似乎不是事件(如CBroe所述),也不是函数(如我所述),而是Window对象。

function a() { console.log(this); }
function x() { console.log(this); }
x.prototype.y = function() { console.log(this); }

a(); // Window
x(); // Window
x.y(); // x

试试下面的东西

 function toDelete(book_id){ var parent = $(event.target).closest("tr"); $.ajax({ type: 'GET', url: 'url-to-delete-book', data:{ book_id: book_id }, success: function(response){ if(response == 'success'){ parent.slideUp(200,function() { parent.remove(); }); } } }); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tbody> <tr> <th>No</th> <th>Title</th> <th>Author</th> <th>Action</th> </tr> <tr> <td>1</td> <td>Harry Potter</td> <td>JK Rowling</td> <td><a href="javascript:;" onclick="toDelete(2)">Delete</a></td> </tr> <tr> <td>2</td> <td>The Great Gatsby</td> <td>F. Scott Fitzgerald</td> <td><a href="javascript:;" onclick="toDelete(1)">Delete</a></td> </tr> </tbody> </table> 

暂无
暂无

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

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