javascript - 使用 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: '© <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);
}
解决方案
看起来你的 hello 方法在 mapData 被实例化之前被调用了。
我看不到它在哪里被实例化,但您可以按如下方式更改您的注册脚本:
ClientScript.RegisterStartupScript(GetType(), "hwa", "createMap(); hello();", true);
请注意,您可能希望向 create 函数添加一个 hello 回调。
有关您在此处尝试执行的操作的更多信息也可能会有所帮助。
推荐阅读
- pandas - 通过 toPandas() 将 pyspark Dataframe 转换为 pandas Dataframe 后,有什么方法可以删除它
- flutter - 表单关闭时如何删除验证
- facebook-marketing-api - Facebook Marketing API 用于个人目标兴趣的转化统计
- python - 如何使用 dnn 修复此打开的 cv 库错误?
- reactjs - Reactjs:使用相同的表单进行添加和更新
- amazon-web-services - 如何正确使用 aws rds describe-events
- javascript - 如何优化 getYoutubeViews 功能以免超过每日 Youtube API 配额?
- php - PHP - mssql_connect():无法连接到服务器
- angular - httppost订阅的angular6结果
- python - 错误:TeleBot:“发生类型错误,args =(”'in
' 需要字符串作为左操作数,而不是 NoneType",)