在全局Javascript变量中保存临时表单信息

时间:2010-07-05 15:17:40

标签: javascript jquery global-variables

我有什么理由不应该做以下事情(避免使用隐藏字段存储临时信息)?我使用jQuery语法简洁,但这是一个普遍的JavaScript问题。

function editComments() {
    window.currentComments = $('#commentsTextBox').val();
    $('#commentsTextBox').removeAttr("readonly");
}

function cancelEditComments() {
    $('#commentsTextBox').val(window.currentComments);
    $('#commentsTextBox').attr("readonly", "readonly");
}

我知道全局变量通常被认为是不好的做法,但是做上述事情真的有问题吗?

请不要回答/评论“全局变量是邪恶的”,除非你能给出理由/解释。

3 个答案:

答案 0 :(得分:4)

除了全局变量是邪恶之外,这没有真正的问题。 ;)

但是,如果您正在使用jQuery,我认为,更好的方法是使用data()将其存储在元素中:

function editComments() {
    $('#commentsTextBox').data("oldValue", $('#commentsTextBox').val());
    $('#commentsTextBox').removeAttr("readonly", "readonly");
}

function cancelEditComments() {
var oldValue = $('#commentsTextBox').data("oldValue");
$('#commentsTextBox').val(oldValue );
$('#commentsTextBox').attr("readonly", "readonly");
}

只要你将它保留在脚本中,并且没有其他任何内容可以使用该元素,那应该可以正常工作。

答案 1 :(得分:3)

javascript中的全局变量问题(除了任何其他语言之外)。是没有解决名称冲突的机制(或者更确切地说,机制是假设它是相同的变量)。如果你使用一个名为currentComments的全局变量,并且还包含一个带有currentComments全局变量的其他模块,那么其中一个将失去,你可能会得到不可预测的结果。

最好使用一个作用于你的模块的一个,因此:

(function(){
    var currentComments;

    function editComments() {
        currentComments = $('#commentsTextBox').val();
        $('#commentsTextBox').removeAttr("readonly", "readonly");
    }

    function cancelEditComments() {
        $('#commentsTextBox').val(currentComments);
        $('#commentsTextBox').attr("readonly", "readonly");
    }
}());

答案 2 :(得分:1)

如果忽略“全局变量不好”这一论点,没有理由不这样做。

您需要注意的一件事是,您无法从IE中的窗口对象中删除属性,它会导致抛出异常。在你的情况下,因为它只是一个字符串,它可能无关紧要。

这在IE上失败了:

window.foo = 'bar';
delete window.foo;