简体   繁体   English

使用 C# 访问 JS 变量

[英]Accessing JS Variables with C#

I've got a variable which is set in a final script tag on page load, as this is required due to accessing the DOM (using a 3rd party library).我有一个变量,它在页面加载时设置在最终脚本标签中,因为这是访问 DOM(使用 3rd 方库)所必需的。 I want to access my variable, however I get "undefined" when accessing it via C# (ASP Web Application).我想访问我的变量,但是在通过 C#(ASP Web 应用程序)访问它时我得到了“未定义”。

How can I access this?我怎样才能访问这个?

If I run the following from C#:如果我从 C# 运行以下命令:

ClientScript.RegisterStartupScript(GetType(), "hwa", "hello();", true);

I get the following error: https://i.stack.imgur.com/veiLB.png我收到以下错误: https : //i.stack.imgur.com/veiLB.​​png

My hello function is:我的问候功能是:

function hello() {
 alert(mapData);
}

This mapData variable is set in a script tag at the end of the body, my original code was to call a JS function AFTER the site loaded, however it comes up as undefined via C# yet shows up if I use the Web Console.这个mapData变量设置在正文末尾的脚本标记中,我的原始代码是在站点加载后调用 JS 函数,但是它通过 C# 显示为未定义但如果我使用 Web 控制台则显示。

Full Script:完整脚本:

function createMap() {
mapData = L.map('map', {
    center: [20.0, 5.0],
    minZoom: 2,
    zoom: 5
});

L.mapData = mapData;

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>',
    subdomains: ['a', 'b', 'c']
}).addTo(L.mapData);
}

function createMarker(long, lat, type) {
    alert(L.mapData);
    L.marker([long, lat], { icon: L.icon({ iconUrl: 'Content/img/' + type + '.png', iconSize: [50, 60], iconAnchor: [22, 94], popupAnchor: [-3, -76], }) }).addTo(L.mapData);
}

function hello() {
    alert(mapData);
}

It looks like your hello method is being called before mapData is being instantiated.看起来你的 hello 方法在 mapData 被实例化之前被调用。

I do not see where it is being instantiated but you could change your register script as follows:我没有看到它在哪里被实例化,但您可以按如下方式更改您的注册脚本:

ClientScript.RegisterStartupScript(GetType(), "hwa", "createMap(); hello();", true);

Note that you may want to add a hello callback to your create function.请注意,您可能希望向 create 函数添加一个 hello 回调。

More info as to what you are trying to do here may also be helpful.有关您在此处尝试执行的操作的更多信息也可能会有所帮助。

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

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