将变量从后面的代码传递给 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18870733/
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 13:29:29  来源:igfitidea点击:

passing a variable to javascript function from code behind

c#javascriptcode-behind

提问by Arianule

I want to pass a string value to a javascript function from code behind. As it is a the moment I get an uncaught reference error explaining that the value is not defined.

我想将一个字符串值从后面的代码传递给一个 javascript 函数。因为这是我收到未捕获的参考错误的那一刻,说明该值未定义。

var variable= txtVariable.Value;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Registering", "RegisterTheUser("+variable+");", true);

Advice perhaps on the correct syntax

可能对正确语法的建议

This is the function

这是功能

function RegisterTheUser(val) {
    alert(val);
}

regards

问候

回答by sbhomra

What you have posted looks fine. I've used the following without any issue:

您发布的内容看起来不错。我使用了以下没有任何问题:

ScriptManager.RegisterStartupScript(this, typeof(string), "Registering", String.Format("RegisterTheUser('{0}');", myVariable), true);

Can you try using the example I have posted?

您可以尝试使用我发布的示例吗?

回答by margabit

The problem might be that your RegisterStartupScriptis being executed before loading the function RegisterTheUser.

问题可能是您RegisterStartupScript在加载函数之前正在执行RegisterTheUser

You need to sort out the order of the loading of the scripts or add some logic to call this function only after the documentis ready.

您需要理清脚本的加载顺序或添加一些逻辑以在document准备好后才调用此函数。

In jQuery is done like this:

在 jQuery 中是这样完成的:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Registering", "$(document).ready(function(){ RegisterTheUser("+variable+"); });", true);

As sbhomra pointed in his answer, if the value is a string you might need to add single qoutes. Not needed if it's a number.

正如 sbhomra 在他的回答中指出的那样,如果该值是一个字符串,您可能需要添加单个 qoutes。如果是数字则不需要。