提供片段名称和真/假变量

时间:2014-11-21 10:43:04

标签: jquery variables

我有一个包含代码的完整文档,我想为其命名=true;变量,然后在 HTML中的<script>标记中调用该名称并且可以将其设置为 false true

我该怎么做?

该片段是:

$(".me").click(function() {
    $(".hidden").fadeIn(500);
});

我将如何做的例子:

enable_click_function: true;

if (self.settings.enable_click_function) {
    self.enableClickFunction();
}

enableClickFunction: function() {
    var self = this;
    $(".me").click(function() {
        $(".hidden").fadeIn(500);
    });
};

jsfiddle

2 个答案:

答案 0 :(得分:1)

您可以使用setter-getter模式。

例如,为您的配置创建定义。用于保存初始值设定项属性的“设置”对象。您的代码段的方法,可以在以后用于打开和关闭事件绑定。像这样:

一个小型的工作演示小提琴:http://jsfiddle.net/abhitalks/ba3zz4b9/5/

<强> 段:

/* Your config definition */
function config() {
    this.settings = {
        "enableEnter": false
    };
    this.executeEnableEnter = function(e) {
        if (e.keyCode == 13){
            $(this).next().focus();
        };
    };
}

/*
  Now you can define getter/setter for each of those settings properties. 
  Setter will use jQuery `.on` and `.off` to bind/unbind the relevant method, 
  depending on your use-case. Something like this:
*/

Object.defineProperty(config.prototype, 'enableEnter', {
    get: function() { return  this.settings.enableEnter; }, 
    set: function(value) {
        this.settings.enableEnter = value;
        if (value) {
            $("input").on("keypress", this.executeEnableEnter);
        } else {
            $("input").off("keypress", this.executeEnableEnter);
        }
    }
});

/*
  Now you can create your config object and use it. 
  For example, if you want to enable enter key behaviour on a checkbox state, 
  then you could:
*/

var configObject = new config;

$("#chk").on("change", function() {
    if (this.checked) { configObject.enableEnter = true; } 
    else { configObject.enableEnter = false; }
  
    $("#result").text("Enter key enabled = " + this.checked + ", Press enter on first input to focus the next.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" /><input type="text" /><hr />
<input id="chk" type="checkbox" /><label for="chk">Enable/Disable Enter</label>
<br /><p id="result"></p>

答案 1 :(得分:0)

我找到了一个更简单的&#34;这样做的方式......

只需在标记中添加:

<script type="text/javascript">
    var enable_fade_in = true;
</script>

这是在外部js文件中

$(function(){
settings={
    enableFadeIn:function() {
        var self = this;
        $(".me").click(function() {
            $(".hidden").fadeIn(500);
        });
    }
}

if ( enable_fade_in ) {
    settings.enableFadeIn();
}

});