我试图在 Razor 条件的 View 中包含一些 JS,但它一直试图将我的 JS 解释为 VB:
@If includeMoreJs Then
@<script type="text/javascript" src="/some-js-file.js"></script>
<script type="text/javascript" src="/some-other-js-file.js"></script>
<script type="text/javascript">
function someFunction(p) {
if (p) foo();
else bar();
}
</script>
End If
我也用 <text>
试过这个此处描述的伪元素:Using Razor within JavaScript
@If includeMoreJs Then
<text>
<script type="text/javascript" src="/some-js-file.js"></script>
<script type="text/javascript" src="/some-other-js-file.js"></script>
<script type="text/javascript">
function someFunction(p) {
if (p) foo();
else bar();
}
</script>
</text>
End If
但仍然没有运气......我怎样才能让 VB 不理会我的 JS?
最佳答案
好吧,我强制自己创建了我的第一个 .vbhtml 文件,然后四处搜索,你已经非常接近 <text>
了。 block 。
This page是 VB Razor 语法的一个很好的资源。
有两种解决方法,具体取决于您的 @If
中有多少 html :
选项 1:@:
这是每一行都需要的,所以通常你只会在你的 If
中只有一行时使用它:
@If includeMoreJs Then
@:<script type="text/javascript" src="/some-js-file.js"></script>
@:<script type="text/javascript" src="/some-other-js-file.js"></script>
@:<script type="text/javascript">
@: function someFunction(p) {
@: if (p) foo();
@: else bar();
@:
@:</script>
End If
..非常漂亮
选项 2:@<text>
因为 VB 可以有 XML,如 this answer 中所述,一个普通的<text>
将被解释为 VB 代码,而不是 Razor 。所以在VB中,相对于C#,需要使用@<text>
有一个 HTML block :
@If includeMoreJs Then
@<text>
<script type="text/javascript" src="/some-js-file.js"></script>
<script type="text/javascript" src="/some-other-js-file.js"></script>
<script type="text/javascript">
function someFunction(p) {
if (p) foo();
else bar();
}
</script>
</text>
End If
这解析得很好。
关于VB Razor 中 <script> 元素中的 Javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27281919/