如何用CSS为含required属性input的对应th设置font-weight?或jQuery实现?
Short answer: No, not with pure CSS right now.
Here's why: CSS selectors work in a "forward-only" direction. To target the <th> that comes before the <td> containing the required <input>, we'd need a way to:
- Target the
<input[required]>element - Jump up to its parent
<td> - Then select the preceding
<th>sibling
Unfortunately, CSS doesn't have a parent selector (to go from child to parent), and while sibling selectors exist, they only let you target elements that come after a reference element—not before. So there's no way to write a CSS rule that reaches back to the earlier <th> based on the input inside the following <td>.
Absolutely! jQuery makes this straightforward with its traversal methods. Here's how to do it cleanly:
First, define a CSS class for the bold styling (better practice than inline styles):
.required-field-label { font-weight: bold; }
Then add this jQuery code to apply the class to the correct <th> elements:
$(document).ready(function() { // Find all inputs with the required attribute $('input[required]') // Traverse up to their closest parent <td> .closest('td') // Select the immediately preceding <th> sibling .prev('th') // Add the bold class to that <th> .addClass('required-field-label'); });
How This Works:
$('input[required]'): Targets every<input>that has therequiredattribute..closest('td'): Moves up the DOM tree to find the nearest<td>parent of the input..prev('th'): Selects the sibling element immediately before that<td>—which is exactly the<th>we want to style..addClass('required-field-label'): Applies our pre-defined bold styling to that<th>.
This will automatically style the corresponding <th> for any required input on your page. If you dynamically add inputs later, you can re-run this code snippet to update the styling.
内容的提问来源于stack exchange,提问作者Jay P.

