简体   繁体   English

在剃刀内调用外部js函数

[英]call external js function within razor

I have this code: 我有以下代码:

Html.RequiresJs("~/Scripts/site/scripts.app.js", 5);
@{

if (String.IsNullOrEmpty(stringQueryElement) && !upcoming.Any())
    {   
        <script type="text/javascript">
            X();
        </script>
    }
}

Inside scripts.app.js file I have a function X() which I want to call out when my if statement is true. scripts.app.js文件中,我有一个函数X(),当if语句为true时,我想调用该函数。 How I call it? 我怎么称呼它? Because the syntax I have now does not work. 因为我现在的语法不起作用。 Did some debugging and I can see that IF statement works correctly. 进行了一些调试,我可以看到IF语句正常工作。 The only question is how do I call my function that is stored in scripts.app.js . 唯一的问题是如何调用存储在scripts.app.js中的函数

Thanks for help in advance. 预先感谢您的帮助。

As your comment stated, your scripts.app.js is injected just before </body> . 如您的评论所述,您的scripts.app.js仅在</body>之前被注入。 This means the script's functions are available after it is evaluated by the browser. 这意味着脚本的功能在浏览器评估后才可用。 Because you try to run your script before that has happened, it won't detect your X() function. 因为您尝试在脚本发生之前运行它,所以它不会检测到您的X()函数。

Use the document ready to make sure all scripts are evaluated: document ready使用document ready ,以确保所有脚本均得到评估:

if (String.IsNullOrEmpty(stringQueryElement) && !upcoming.Any())
    {   
        <script type="text/javascript">
            $(function() {
                X();
            });
        </script>
    }
}

(Assuming you're using jQuery) (假设您使用的是jQuery)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM