突出显示包含的字符串

时间:2018-03-12 12:23:36

标签: javascript jquery

我想加粗包含Running test的所有行,而不是只突出显示Running test。

我不知道前面有什么,所以我想突出显示正在运行测试的行。

//highlight words in the results
    $("p").html(function() {
        return $(this).html()
            .replace("Running test:", '<strong>Running test:</strong>')       
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Running test: test1</p>
<p>ssfafasf</p>
<p>Running test: test2</p>
<p>gsgsddsh</p>

4 个答案:

答案 0 :(得分:0)

您可以设置条件,以验证内容是否包含特定字符串...

&#13;
&#13;
public class ViewModel : Microsoft.VisualStudio.PlatformUI.ObservableObject
{
    private Model mSelectedModel;
    public Model SelectedModel
    {
        get { return mSelectedModel; }
        set
        {
            SetProperty(ref mSelectedModel, value);
            NotifyPropertyChanged(nameof(IsSelectedModelChecked));
        }
    }

    private ObservableCollection<Model> mModels = new ObservableCollection<Model>();
    public ObservableCollection<Model> Models
    {
        get { return mModels; }
        set { SetProperty(ref mModels, value); }
    }

    public bool IsSelectedModelChecked => SelectedModel?.IsChecked ?? false;
}
&#13;
//highlight words in the results
    $("p").html(function() {
      if($(this).html().includes("Running test:")){
             return '<strong>'+$(this).html()+'</strong>';
            
      }
      else  return $(this).html();
            
    })
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用class的解决方案,检查每个p元素是否包含Running test:,然后添加类。

&#13;
&#13;
$("p").each(function() {
  if ($(this).html().indexOf("Running test:") >= 0) {
  $(this).addClass('makeItBold');
  } else {
  $(this).removeClass('makeItBold');
  }
});
&#13;
.makeItBold {
font-weight: bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Running test: test1</p>
<p>ssfafasf</p>
<p>Running test: test2</p>
<p>gsgsddsh</p>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

//highlight words in the results
    $("p").html(function() {
         if($(this).html().indexOf('Running test') !== -1)
         {
         $(this).addClass('highlight');
         }
                
    })
.highlight
{
font-weight : bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Running test: test1</p>
<p>ssfafasf</p>
<p>Running test: test2</p>
<p>gsgsddsh</p>

答案 3 :(得分:0)

您可以创建一个class并根据以下条件将其应用于段落。使用:contains检查段落中是否有特定文字。

&#13;
&#13;
$("p:contains('Running test:')").addClass("bold");
&#13;
.bold {
  font-weight:bold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Running test: test1</p>
<p>ssfafasf</p>
<p>Running test: test2</p>
<p>gsgsddsh</p>
&#13;
&#13;
&#13;

如果您不想创建class,请直接应用下面的粗体样式。

$("p:contains('Running test:')").css("fontWeight","bold");