javascript 如何从mvc视图调用java脚本函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16303085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:07:57  来源:igfitidea点击:

How to call java script function from mvc view

javascriptjqueryasp.net-mvcasp.net-mvc-3

提问by RWendi

Let say I have the following javascript

假设我有以下 javascript

function blob(alertText) {
     alert(alertText);
}

I would like to call the function within my view. something like:

我想在我的视图中调用该函数。就像是:

<% if (x == 0)
    //Need to Call the javascript function here. e.g. blob("sometext");
%>

How can I call the the javascript function within the enclosed if statement in my view?

在我的视图中,如何在封闭的 if 语句中调用 javascript 函数?

回答by Ian

Try:

尝试:

<% if (x == 0) { %>
    <script type="text/javascript">blob("sometext");</script>
<% } %>

Since the Javascript needs to be put on the page, you need to close off the <% %>tags so that you can print HTML. The specific HTML needs to be a <script>tag that calls the function you need.

由于需要在页面上放置 Javascript,因此您需要关闭<% %>标签,以便您可以打印 HTML。特定的 HTML 需要是一个<script>调用你需要的函数的标签。

回答by Richard Dalton

Put a script tag calling the javasript function inside the if statement:

在 if 语句中放置一个调用 javasript 函数的脚本标签:

<% if (x == 0) { %>
    <script type="text/javascript">blob("sometext");</script>
<% } %>

回答by pollirrata

I know that you're not using Razor (because of your code sample), but if you want to use it at some time, you can do it like this

我知道你没有使用 Razor(因为你的代码示例),但如果你想在某个时候使用它,你可以这样做

@if (x == 0)
{
<text>
    <script type="text/javascript">blob("sometext");</script>
</text>
}

or

或者

@if (x == 0)
{
@:    <script type="text/javascript">blob("sometext");</script>
}

回答by pollirrata

@if (x == 0)
{
    <script type="text/javascript">blob("sometext");</script>
}