未捕获的语法错误:无效或意外的标记。

41

我有一个 Razor 语法,像这样:

   foreach(var item in model)
 {
<td><a href ="#"  onclick="Getinfo(@item.email);" >6/16/2016 2:02:29 AM</a>  </td>
 }

我接收请求的 JavaScript 代码如下:

<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
    function Getinfo(elem) {
        var email = document.getElementById(elem).innerHTML;
    }
</script>

点击href链接时,我在浏览器控制台中看到以下错误:

 

"Uncaught SyntaxError:Invalid or unexpected token"

而且这部分被划线了:

    **</a>  </td>**

我是一个初学者,所以经常卡在语法上。如果是这样的话,请帮帮我。

3个回答

68

您应该在引号中传递 @item.email,这样它将被视为字符串参数。

<td><a href ="#"  onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a>  </td>
否则,它被视为变量,因此会生成错误。

谢谢,这很有帮助。我正在使用 Ruby on Rails 并遇到了相同的错误。 - Kangkan

16

如果你只有一行字符串(电子邮件),那么接受的答案有效,但是如果你有多行字符串,那么错误仍然存在。

请注意这个问题:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

将Getinfo中的单引号(')改为反引号(`),错误将得到修复:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

1

在这种情况下,我也遇到了多行字符串的问题。@Iman的反引号(`)解决方案在现代浏览器中效果很好,但在Internet Explorer中会导致无效字符错误。我不得不使用以下方法:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

然后我不得不在js函数中再次添加回车符。必须使用正则表达式来处理多个回车符。

// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接