在提出问题之前,这是一个示例代码。
<tr>
<th>Name</th>
<td><input type="text" required></td>
<th>Age</th>
<td><input type="text"></td>
</tr>
如果th
标记下的input
标记具有td
属性,我想要将required
标记的html设置为粗体。< / p>
我怀疑它是否因为有条件而无法实现。在那种情况下,有没有办法在jQuery中做到这一点?
答案 0 :(得分:2)
由于CSS中没有以前的兄弟,因此无法使用CSS 请查看此链接了解更多详情 - Is there a "previous sibling" CSS selector?
要达到预期效果,请使用以下选项
使用 $(&#39; td输入&#39;)
使用 .each 方法循环遍历 td 标记内的所有输入字段
检查所需属性
如果找到,请获取输入即td 的父元素和td 即的前一元素并应用css- font-weight
$('td input').each(function(i){
console.log(i)
if($(this).attr("required")=='required'){
console.log($(this).parent().prev())
$(this).parent().prev().css('font-weight', 'bold')
}
})
&#13;
代码示例 - https://codepen.io/nagasai/pen/ZoEVYN
注意 - 默认情况下,字体粗体为粗体,只是为了差异,我在codepen中将 标记字体粗体设为正常
答案 1 :(得分:0)
您可以使用$('input:required').parent().prev().addClass("required");
为所需输入的所有标头添加所需的类,然后在css中使用该类来加粗它。如果我没有弄错,css选择器不能选择以前的元素,所以没有纯css解决方案。
$('input:required').parent().prev().addClass("required");
th {
font-weight: normal;
}
th.required {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Name</th>
<td><input type="text" required></td>
<th>Age</th>
<td><input type="text"></td>
</tr>
</table>
答案 2 :(得分:0)
CSS中没有先前的兄弟选择器和父选择器。 然而,有一个下一个兄弟选择器,这使得使用这个单线程实现最小,优雅和不易出错的解决方案成为可能:
$("th ~ td>input:required").parent().prev().addClass("required");
美丽(以及除了之前的答案)是这个选择器 ONLY 选择输入标签:
和强>
...从而消除了parent().prev()
对于具有不同结构的表失败的风险。
以下是代码笔链接:https://codepen.io/anon/pen/XqWoJr