如何在Angular DataTables中为表格整行添加超链接
Alright, I see what you need—making the entire table row clickable to open the corresponding detail page instead of just the single link column. Let's tweak your existing DataTables setup to get that working smoothly:
Modified Code
<table class="display" id="example"> <thead> <tr> <th>Information</th> <th>Link</th> </tr> </thead> </table> <script> var responseObj = [ { "information": "A1", "weblink": "http://www.microsoft.com" }, { "information": "A2", "weblink": "http://www.yahoo.com" }, { "information": "A3", "weblink": "http://www.google.com" }, { "information": "A4", "weblink": "http://www.duckduckgo.com" } ]; $('#example').dataTable({ "data": responseObj, "columns": [ { "data": "information" }, { "data": "weblink", "render": function(data, type, row, meta){ if(type === 'display'){ data = '<a href="' + data + '">' + data + '</a>'; } return data; } } ], // Callback triggered when a new row is rendered "createdRow": function(row, data, dataIndex) { // Add visual cue that the row is interactive $(row).css('cursor', 'pointer'); // Bind click event to the entire row $(row).on('click', function() { window.location.href = data.weblink; }); } }); </script>
Key Changes Explained
createdRowCallback: This DataTables hook runs every time a new row is added to the table. We use it to:- Add a
cursor: pointerstyle so users immediately know the row is clickable. - Attach a click event that redirects to the row's corresponding
weblinkURL when any part of the row is clicked.
- Add a
- Preserved Link Column: I kept your original link column intact in case you still want that direct text link option—if you don't need it, just remove that column from the
columnsarray.
Optional: Fix Double Navigation on Link Column
If you don't want the link column to trigger two navigation events (one from the row, one from the link itself), add this small adjustment to the link render function:
"render": function(data, type, row, meta){ if(type === 'display'){ data = '<a href="' + data + '" onclick="event.stopPropagation();">' + data + '</a>'; } return data; }
The event.stopPropagation() stops the click event from bubbling up to the row, so only the link's navigation runs when clicking that specific column.
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

