我有 2 个按钮,用于更改变量的状态,如果状态为 1,则显示 div,如果不是,则隐藏 div。我需要捕获此变量更改并在不同脚本中添加条件,这将无需刷新页面即可工作,并且将根据变量添加或隐藏脚本。 下面是示例代码:
var point_access = 0;
document.getElementById('button 1').onclick = function() {
if (point_access == 0) {
point_access = 1;
//do smth else
}
}
document.getElementById('button 2').onclick = function() {
if (point_access == 1) {
point_access = 0;
//do smth else
}
}
这是我想要显示或隐藏脚本的代码,这取决于变量point_access
map = new ol.Map({
layers: [
new ol.layer.Tile({
//smth here
}),
new ol.layer.Tile({
//smth here
}),
vectorLayer //this is the variable inside script which i want to show or hide
//if(point_access == 1){
// vectorLayer
//}
],
//smth else
});
那么,我怎样才能做到实时工作呢?它始终将 point_access
值设为 0
并且不监听我点击时的值更改。
最佳答案
问题在于,您想要对变量更改使用react的代码在变量更改时已经运行。您需要让它再次运行以重新检查变量。如果没有其余的代码,我无法确切地看到这是如何发生的,但您需要重新声明 map 或更新它。
例如:
document.getElementById('button 1').onclick = function() {
if (point_access == 0) {
point_access = 1;
updateTheMap();
//do smth else
}
}
或者,您可以将变量转换为对象:
point_access = {
value: 0,
updateValue: function(value) {
this.value = value;
updateTheMap();
}
}
然后您可以通过point_access.value
获取point_access
的值并通过point_access.updateValue(1)
设置它,以及 map 将更新:
document.getElementById('button 1').onclick = function() {
if (point_access == 0) {
point_access.updateValue(1);
//do smth else
}
}
当然,您仍然需要提供一个 updateTheMap
函数。
关于javascript - js 捕获变量是否被 js 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54254637/