如何使用jQuery在指定data-category-id的<tr>前添加新<tr>元素?
jQuery makes inserting elements before a target element straightforward, and using the data-category-id attribute is the perfect way to pinpoint exactly where you want to add your new <tr>.
Here's how to implement this:
Basic Example (Insert HTML String)
You can directly pass an HTML string to the before() method to quickly insert your new row:
// Target the specific <tr> using its data attribute const targetRow = $('tr[data-category-id="14"]'); // Insert a new <tr> immediately before it targetRow.before('<tr><td colspan="100">This is the new row added before category 14</td></tr>');
Dynamic Element Creation (For More Control)
If you need to build the new row programmatically (e.g., adding custom classes, event listeners, or dynamic content), create the element with jQuery first:
// Build the new row and its content const newRow = $('<tr>').addClass('custom-new-row'); const newCell = $('<td>').text('Dynamically generated row content').appendTo(newRow); // Insert it before the target row $('tr[data-category-id="14"]').before(newRow);
Handling Multiple Matching Rows
If there are multiple <tr> elements with data-category-id="14", the above code will insert the new row before each matching row. To target only the first occurrence, use:
// Option 1: Use .first() method $('tr[data-category-id="14"]').first().before('<tr>...</tr>'); // Option 2: Use :first selector $('tr[data-category-id="14"]:first').before('<tr>...</tr>');
The core idea here is using jQuery's attribute selector ([data-category-id="14"]) to precisely target the row you want, then using the before() method to insert your new element right where you need it.
内容的提问来源于stack exchange,提问作者Daniel

