在 razor foreach 语句中调用 JS 函数

call JS function inside razor foreach statement

本文关键字:调用 JS 函数 语句 razor foreach      更新时间:2023-09-26

我有一个Model LevelInfo属性:

public IEnumerable<Tuple<string, string, string>> LevelInfo { get; set; }

在视图中,我有一个JS函数:

function fillPath(level, color) {
        $('[level=' + level).attr({ 'fill': color });
    }

现在我想遍历LevelInfo并调用fillPath函数:

$(document).ready(function() {
        @foreach (var info in Model.LevelInfo)
        {
            // How can I call JS function from here?
            // i.e,  fillPath(info.Item1, info.Item2)
        }
    });

谢谢。

请记住,@foreach 在服务器端执行,并为 {} 之间的内容发出 HTML。

只需在括号之间写 JavaScript。

$(document).ready(function() {
    @foreach (var info in Model.LevelInfo)
    {
        fillPath(info.Item1, info.Item2) // Assumes this is a function defined in JavaScript elsewhere
    }
});

Razor 有时在识别从服务器端代码到客户端代码的转换方面有点挑剔。 您可能需要将 JavaScript 代码包装在 <text> 中以帮助 Razor 运行。