简体   繁体   English

使用jQuery / Javascript从MVC模型解析和修改HTML

[英]Parse and modify HTML from MVC Model using jQuery / Javascript

This needs to be done on the client (please trust me, I'll save the explanation). 这需要在客户端上完成(请相信我,我将保存说明)。

I have a razor view that renders partial views in a loop. 我有一个剃刀视图,可在循环中呈现部分视图。 viewModel is just another class. viewModel只是另一个类。

@{
  foreach (ObjectName objInstance in Model.Collection)
  {
    @Html.Parial(partialViewName, viewModel)
  }
}

And the partial view ultimately renders HTML from a viewModel property (this obviously occurs many times since this partial view is rendered in a loop). 最终,部分视图从viewModel属性呈现HTML(这显然发生了很多次,因为此部分视图是在循环中呈现的)。

@Html.Raw(Model.GetPropertyTextValue())

The HTML from GetPropertyTextValue() can look something like this: 来自GetPropertyTextValue()的HTML看起来可能像这样:

<ul>\r\n<li>2,3,6-Tri-O-methyl-D-glucose (<a target=\"_blank\" href=\"http://www.blahblah.com/pubmed/12345?name=value\">1</a>) , 2,3,6-tri-O-methyl-D-mannose, 3-O- blah blah</ul>

I need to take the value in Model.GetPropertyTextValue and parse through it, replacing the entire URL (to blahblah.com) with a different link (but keep any numbers like the "12345"). 我需要在Model.GetPropertyTextValue中获取值并进行解析,用不同的链接替换整个URL(至blahblah.com)(但请保留任何数字,例如“ 12345”)。 Such URLs could appear multiple times in the string. 此类URL在字符串中可能出现多次。

I believe this should be done with jQuery/Javascript, but I'm not sure how to approach it. 我相信这应该使用jQuery / Javascript完成,但是我不确定如何实现。 Can anyone please suggest how to go about this? 有人可以建议如何解决吗? Thank you. 谢谢。

If you absolutely have to do on the client side, you can try something like this. 如果您绝对必须在客户端执行此操作,则可以尝试这样的操作。 First wrap your generated content with an identifiable div, so that you will be able to act within that container only: 首先,使用可识别的div包装您生成的内容,这样您就只能在该容器内操作:

<div id="items-to-parse">
    @{
      foreach (ObjectName objInstance in Model.Collection)
      {
        @Html.Partial(partialViewName, viewModel)
      }
    }
</div>

Then create a simple script that searches for all links within that container and changes their href attribute: 然后创建一个简单的脚本,搜索该容器内的所有链接并更改其href属性:

    $('#items-to-parse a').each(function() {
        $(this).attr('href', 'http://the.new.url');
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM