当标签具有" required"时,如何在特定标签的父标签上设置font-weight。使用css属性?

时间:2018-04-18 19:04:28

标签: jquery css

在提出问题之前,这是一个示例代码。

<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中做到这一点?

3 个答案:

答案 0 :(得分:2)

由于CSS中没有以前的兄弟,因此无法使用CSS 请查看此链接了解更多详情 - Is there a "previous sibling" CSS selector?

要达到预期效果,请使用以下选项

  1. 使用 $(&#39; td输入&#39;)

  2. 循环td标记内的所有输入字段
  3. 使用 .each 方法循环遍历 td 标记内的所有输入字段

  4. 检查所需属性

  5. 如果找到,请获取输入即td 的父元素和td 的前一元素并应用css- font-weight

  6. &#13;
    &#13;
        $('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;
    &#13;
    &#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 选择输入标签:

  • 标记为 required

  • 位于 td 标记内,并带有前面的 兄弟

...从而消除了parent().prev()对于具有不同结构的表失败的风险。

以下是代码笔链接:https://codepen.io/anon/pen/XqWoJr