仅当Boolean为true时才运行JavaScript函数

时间:2013-07-12 13:00:52

标签: javascript

我试图让OpenLayers的功能只有在用户打开的情况下才能工作。我已经制作了html按钮,调用函数将布尔变量clickSearch转换为true。如何使该功能仅适用于clicksearch = true?是某种if语句吗?

这是运行我要打开和关闭的功能的代码:

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {                
            defaultHandlerOptions: {
                'single': true,
                'double': false,
                'pixelTolerance': 0,
                'stopSingle': false,
                'stopDouble': false
            },

            initialize: function(options) {
                this.handlerOptions = OpenLayers.Util.extend(
                    {}, this.defaultHandlerOptions
                );
                OpenLayers.Control.prototype.initialize.apply(
                    this, arguments
                ); 
                this.handler = new OpenLayers.Handler.Click(
                    this, {
                        'click': this.trigger
                    }, this.handlerOptions
                );
            }, 

            trigger: function(e) {
                var lonlat = map.getLonLatFromPixel(e.xy);
                alert("You clicked near " + lonlat.lat + " N, " +
                                          + lonlat.lon + " E");
            }
            });

这些函数打开和关闭布尔clickSearch

var clickSearch= false;

function turnOn(){ clickSearch=true};
function turnOff(){ clickSearch=false};

这些按钮调用该函数打开/关闭clickSearch

<button onclick="turnOn()">Turn on click-to-search</button>
<button onclick="turnOff()">Turn off click-to-search</button>

1 个答案:

答案 0 :(得分:2)

如果希望它有效,只需检查您的布尔值。例如,在您的触发器功能中:

trigger: function(e) {
    if (!clickSearch)
        { return; }
    // ...
}