首页 > 解决方案 > 使用 C# 访问 JS 变量

问题描述

我有一个变量,该变量在页面加载时的最终脚本标记中设置,因为这是访问 DOM 所必需的(使用第 3 方库)。我想访问我的变量,但是通过 C#(ASP Web 应用程序)访问它时我得到“未定义”。

我怎样才能访问这个?

如果我从 C# 运行以下命令:

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

我收到以下错误: https ://i.stack.imgur.com/veiLB.​​png

我的 hello 函数是:

function hello() {
 alert(mapData);
}

mapData变量设置在正文末尾的脚本标记中,我的原始代码是在站点加载后调用 JS 函数,但是它通过 C# 显示为未定义,但如果我使用 Web 控制台则显示。

完整脚本:

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);
}

标签: javascriptc#webforms

解决方案


看起来你的 hello 方法在 mapData 被实例化之前被调用了。

我看不到它在哪里被实例化,但您可以按如下方式更改您的注册脚本:

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

请注意,您可能希望向 create 函数添加一个 hello 回调。

有关您在此处尝试执行的操作的更多信息也可能会有所帮助。


推荐阅读