如何在jQuery动态追加的按钮中实现Font Awesome图标?
Hey there! Let's get that Font Awesome trash icon in your delete button sorted out. Here's the correct approach:
First, a quick heads-up: Your original code uses an <input type="submit"> element, which can't contain child elements (like the Font Awesome icon tag). We'll need to switch that to a <button> element instead, since buttons can hold nested content. Also, the correct Font Awesome class is fa fa-trash (you had a small typo with fa-fa-trash).
Here's your updated function:
function dataTable(data) { var row = $('<tr id=' + data.id + '/>'); $('#table').append(row); // Replace input with button, add Font Awesome icon row.append($( '<td><button class="btn btn-danger" onclick="remove(' + data.id + ')"><i class="fa fa-trash"></i></button></td>' )); }
If you prefer cleaner, more maintainable code, you can use ES6 template strings to avoid messy string concatenation:
function dataTable(data) { const row = $(`<tr id="${data.id}"/>`); $('#table').append(row); row.append(`<td><button class="btn btn-danger" onclick="remove(${data.id})"><i class="fa fa-trash"></i></button></td>`); }
A couple of important reminders:
- Make sure you've included the Font Awesome CSS in your project (via CDN or local files) — without this, the icon won't render at all.
- If you're using Font Awesome 5 or newer, the class names are updated: use
fas fa-trash(for the solid style) instead offa fa-trash. Adjust the class based on your Font Awesome version and desired icon style.
内容的提问来源于stack exchange,提问作者termlim
相关产品推荐
相关产品推荐

