【问题标题】:jQuery - change font-weight of specific text with same class name [duplicate]jQuery - 更改具有相同类名的特定文本的字体粗细[重复]
【发布时间】:2020-06-10 17:14:03
【问题描述】:

我有两个类名相同的 div:

<button>Click to change font weight.</button>

<div class="wt">Paragraph 1</p>
<div class="wt">Paragraph 2</p>

使用 jQuery,我正在尝试更改将“第 1 段”作为文本的 div 的字体粗细。解决这个问题的最佳方法是什么?这就是我正在尝试的 - 但它当然会将两个 div 的文本设置为粗体:

  $("button").click(function(){
    if($(".wt").text().trim() == "Paragraph 1")
    {
        $(".wt").css("font-weight","bold" )  
    }
  });
});

【问题讨论】:

    标签: javascript jquery user-interface frontend


    【解决方案1】:

    你可以使用 jQuery contains() 方法:

    $(".wt:contains(Paragraph 1)").css("font-weight","bold" )
    

    【讨论】:

      【解决方案2】:

      对于您的查询,我会添加类:

      $('.wt:first').addClass('font-weight-bold');
      

      如果您使用的是 bootstrap 4,它将自动支持该类。否则,请在样式表中添加此规则:

      .font-weight-bold {
        font-weight: bold;
      }
      

      如果您的段落不是 DOM 树中的第一个段落并且正在寻找文本,则按照其他答案中的建议使用包含选择器:

      $('.wt:contains("Paragraph 1")').addClass('font-weight-bold');
      

      最后一件事,我忘了提到您可以使用 toggleClass 在按钮单击时切换更改。

      $('.wt:first').toggleClass('font-weight-bold');
      

      【讨论】:

      【解决方案3】:

      您可以使用 jQuery 的 :contains() 选择器。

      我添加了一些额外的功能,以便您可以在font-weight 之间切换。值得注意的是,使用 jQuery 调用 .css('font-weight') 不会返回诸如 normalbold 之类的字符串值;相反,调用它会检索数字('400' === 'normal''700' === 'bold' 等)。

      $("button").click(function() {
        let par1 = $(".wt:contains('Paragraph 1')");
      
        // Toggle between font-weights
        par1.css(
          'font-weight',
          (['normal', '400'].indexOf(par1.css('font-weight')) === -1) ? 'normal' : 'bold'
        );
      
        // Or, uncomment and use this if you do not wish to toggle the div
        // par1.css('font-weight', 'bold');
      });
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      
      <button>Click to change font weight.</button>
      
      <div class="wt">Paragraph 1</div>
      <div class="wt">Paragraph 2</div>

      希望这会有所帮助,

      【讨论】:

        【解决方案4】:
         $("button").click(function(){
           $(".wt").each(function(){
             if($(this).text() == "Paragraph 1")
             $(this).css("font-weight","bold");
           });
         });
        

        【讨论】:

        • 请编辑您的答案,并附上代码 sn-p 的文字说明,并解释它是如何回答问题的
        猜你喜欢
        • 2017-04-13
        • 1970-01-01
        • 2013-06-06
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 2015-07-31
        • 1970-01-01
        相关资源
        最近更新 更多