简体   繁体   中英

Using a HTML hyperlink to call a JS function on the parent element

I have an HTML table as shown below. At the end of each non-header row, I have two links, one for copy and one for edit. When clicked, they should trigger a JavaScript function that is defined below.

 function editRow(el) { //alert function added for debug purposes alert(el.rowIndex); } 
 <table> <tr> <th>Date</th> <th>Tools</th> </tr> <tr> <td>20 October 2017</td> <td> <a href="javascript:editRow(this)">Edit</a> <a href="javascript:copyRow(this)">Copy</a> </td> </tr> <tr> <td>19 October 2017</td> <td> <a href="javascript:editRow(this)">Edit</a> <a href="javascript:copyRow(this)">Copy</a> </td> </tr> </table> 

However, the alert always says undefined . I think this is because the hyperlink is calling the function on the text and not the cell. How can I change the editRow(this) call to one that calls it on its parent element? I tried editRow(parent) and editRow(this.parent) but it didn't do anything useful.

Your problem is that when calling javascript using javascript: editRow(this) , the this is set to the window object

You can fix your code by installing the handlers from HTML, but you really should do it from JS.

Added an example below using the onclick HTML attribute for simplicity.

 function editRow(obj) { console.log('edit handler tagname', obj.tagName); } function copyRow(obj) { console.log('copy handler parent tr rowIndex', obj.parentElement.parentElement.rowIndex); } 
 <table> <tr> <th>Date</th> <th>Tools</th> </tr> <tr> <td>20 October 2017</td> <td> <a onclick="editRow(this)" href="#">Edit</a> <a onclick="javascript:copyRow(this)" href="#">Copy</a> </td> </tr> <tr> <td>19 October 2017</td> <td> <a onclick="editRow(this)" href="#">Edit</a> <a onclick="copyRow(this)" href="#">Copy</a></td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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