使用JavaScript在Asp.net MVC中突出显示html文档表达式 [英] Highlighting an html document expression in Asp.net mvc using JavaScript

查看:97
本文介绍了使用JavaScript在Asp.net MVC中突出显示html文档表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示在网络浏览器上显示的html文档中的特定句子.

I'm trying to highlight a specific sentence in an html document displayed on the web browser.

我的控制器中有此操作:

I have this action in my controller:

public ActionResult GetHtmlPage(string path)
{
    return new FilePathResult(path, "text/html");
}

,我有这个视图,该视图显示了指定路径中的html文档.

and I have this view that shows the html document in the specified path.

@model TextPlagiarismWebApp.Models.ViewModels.ManageDocumentViewModel

@{
    ViewBag.Title = "ManageDocument";
}

<h2>ManageDocument</h2>

@Html.Action("GetHtmlPage", "Upload", new { path = Model.documentPath })

<script type="text/javascript">
    var sen = @Model.sentence["sentence"];
    $("div:contains('" + sen + "')").html(function (_, html) {
        var regex = new RegExp("(" + sen + ")", "g");
        return html.replace(regex, '<span style="background-color:#FFFF00">$1</span>');
    });
</script>

我调试了程序,并且sen变量是我期望的:

I debugged the program and the sen variable is what I would expect:

var sen = @Model.sentence["sentence"];

尽管如此,它并没有突出显示我要查找的特定句子.它只显示原始的html文档.

But despite that, it's not highlighting the specific sentences that I'm looking for. It only shows the original html document.

让我们举一个例子,在我确定该句子存在的地方:

Let's take this example where I'm sure the sentence exists:

var sen = "Requirements for breeding tanks vary with each species. Separate tanks may be required."

HTML:

<p class=MsoNormal style='text-align:justify;mso-layout-grid-align:none;
text-autospace:none'><span lang=EN-AU style='color:black'>Requirements for
breeding tanks vary with each species. Separate tanks may be required.<o:p>
</o:p></span></p>

但是该句子未突出显示,我不知道为什么.

But the sentence is not highlighted, and I can't figure out why.

有什么问题的建议吗?

推荐答案

您可以这样做

  $("body").html(function (_, innerHTML) {
        var regex = new RegExp("(" + sen + "'))", "g");
        return innerHTML.replace(/\s\s+/g, ' ').replace(/\r?\n|\r/g, '').replace(regex, '<span style="background-color:#FFFF00">$1</span>');
    });

第一次替换将.replace(/\s\s+/g, ' ')删除多个空格,并且.replace(/\r?\n|\r/g, '')删除段落中的换行符

the first replace will .replace(/\s\s+/g, ' ') will remove multiple spaces and .replace(/\r?\n|\r/g, '') will remove the break line in paragraph

这是示例 https://jsfiddle.net/jz86v8we/10/

修改

您可以使用 Jquery-Highlight- 5.js 通过添加

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<script src="http://johannburkard.de/resources/Johann/jquery.highlight-5.js"></script>

并在脚本中使用

$("body").highlight("The Business");

并将其添加到您的css文件

.highlight { background-color: yellow }

这篇关于使用JavaScript在Asp.net MVC中突出显示html文档表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆