我的现有代码在 jquery 1.10.2 之前工作正常。我尝试在 Debug模式下运行,似乎<text>
中的代码尚未达到。 CalculteMyAgeOne 已达到,而CalculateMyAgeTwo 从未达到。我在 View 中有以下代码。为什么它不执行 <text>
中的代码不再了吗?
注意: 我已经添加了 AddRows 函数,并且在 Debug模式下达到了 AddRows 函数,但是,CalculateMyAgeTwo 的情况并非如此
<script type="text/javascript">
$(function () {
CalculateMyAgeOne();
@if (Mode)
{
<text>
CalculateMyAgeTwo();
AddRows(@(5 - Model.Rows.Length));
</text>
}
});
function CalculateMyAgeOne() {
$("#table tbody tr:last").hide();
}
@if (Mode){ //Note that Mode is true
<text>
function CalculateMyAgeTwo() {
}
function AddRows(rowsToAdd){
}
</text>
}
最佳答案
既然您已经标记了 ASP MVC,我想澄清一下 <text>
element 是一个特殊的 Razor 元素(Razor 是一个具有自己语法的 ASP MVC View 引擎),与 JavaScript 或 HTML 无关。来自 this excellent post介绍 ASP MVC 中 Razor 语法的一些内容:
The tag is an element that is treated specially by Razor. It causes Razor to interpret the inner contents of the block as content, and to not render the containing tag element (meaning only the inner contents of the element will be rendered – the tag itself will not). This makes it convenient when you want to render multi-line content blocks that are not wrapped by an HTML element.
要使其正常工作,<text>
元素必须位于 Razor 代码块内。否则,它将按生成的 HTML 上的原样呈现(在您的情况下会导致语法错误)。
假设此脚本元素位于 Razor View 内,以下代码:
<script type="text/javascript">
$(function () {
CalculateMyAgeOne();
<text>
CalculateMyAgeTwo();
</text>
});
function CalculateMyAgeOne() {
alert("CalculateMyAgeOne");
}
function CalculateMyAgeTwo() {
alert("CalculateMyAgeTwo");
}
</script>
将完全按照发送到浏览器的 HTML 上的方式呈现,并且您会收到语法错误,正如其他人已经指出的那样。 (基本上不会看到任何警报)。
但是,如果您有 <text>
Razor View 中代码块内的元素,如本示例所示:
<script type="text/javascript">
$(function () {
CalculateMyAgeOne();
@if ( true /* some meaningful condition in real code */ ) {
<text>
CalculateMyAgeTwo();
</text>
}
});
function CalculateMyAgeOne() {
alert("CalculateMyAgeOne");
}
function CalculateMyAgeTwo() {
alert("CalculateMyAgeTwo");
}
</script>
然后,当条件为真时,将呈现结果 HTML:
<script type="text/javascript">
$(function () {
CalculateMyAgeOne();
CalculateMyAgeTwo();
});
function CalculateMyAgeOne() {
alert("CalculateMyAgeOne");
}
function CalculateMyAgeTwo() {
alert("CalculateMyAgeTwo");
}
</script>
如果条件为假,则调用CalculateMyAgeTwo
不会被渲染。如果删除 <text>
在最后一个示例中,Razor 会认为 CalculateMyAgeTwo
元素是服务器端 C# 代码的一部分,您会在渲染 View 时遇到服务器端错误。
希望对你有帮助!
关于jquery - <text> 中的代码不再执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24505516/