这个问题是伟大问题Mix Razor and Javascript code的尾声。我在哪里了解此语法:
@if (foo)
{
// C# code
<text>
// JS Code
</text>
}
它运行良好,直到今天,当我在 <text></text>
中使用 JS 正则表达式时:
$('#bar').html(boo.replace(/<br([\/ ]*)>/g, "\r\n"));
这会抛出一个黄页,告诉我 br(
有问题无法分析。
有没有内联的方法来处理它?</p>
最佳答案
(替换我之前的答案)
我在 MVC View 中测试了这段代码,它有效:
<div id="bar" style="border: 1px solid black">
Dummy content (should be replaced)
</div>
<script type="text/javascript">
var boo = "<span>hello<br />world</span>";
var symbolLT = "<";
@if (1 == 1)
{
// C# code
<text>
var regex = new RegExp(symbolLT + "br([\/ ]*)>", "g");
$('#bar').html(boo.replace(regex, "\r\n"));
</text>
}
</script>
诀窍是隔离 "<"
来自 <text></text>
的字符 block ,和使用 new RegExp()
。也许比普通的内联表达式可读性差一些,但它确实有效。
或者您可以简单地在页面前面创建正则表达式,这样就可以在 <text></text>
之外 block ,然后在里面使用它。
关于javascript - 当我混合 razor 和 JS 并使用 <text> </text> 时,正则表达式出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40179095/