在全局的Javascript变量中保存临时表单信息
是否有任何理由不应该这样做(避免使用隐藏字段来存储临时信息)?为简洁起见,我使用jQuery语法,但这是一个常见的JavaScript问题。在全局的Javascript变量中保存临时表单信息
function editComments() {
window.currentComments = $('#commentsTextBox').val();
$('#commentsTextBox').removeAttr("readonly");
}
function cancelEditComments() {
$('#commentsTextBox').val(window.currentComments);
$('#commentsTextBox').attr("readonly", "readonly");
}
我知道全局变量一般被认为是不好的做法,但是真的有这个问题吗?
请不要回答/评论与“全局变量是邪恶的”,除非你可以给出一个理由/解释。
除了全局变量是邪恶之外,这里没有真正的问题。 ;)
但是,如果你是无论如何使用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");
}
只要你保持它在脚本中,并没有其他事情做的元素,这应该工作得很好。
我喜欢这种方式,谢谢。 – fearofawhackplanet 2010-07-05 16:03:12
jQuery.data()的jQuery文档(http://api.jquery.com/jQuery.data/)表示这是一个“低级方法”,您应该使用'.data()'而不是。你知道这意味着什么,为什么? – 2010-07-05 16:33:44
// @Lèse很好赶,谢谢!我更正了代码。 “高级”'.data(key,value)'是'$(element)'对象的直接方法(而不是'jQuery.data(elementname,key,value)') – 2010-07-05 16:38:50
如果忽略“全局变量不好”的说法,没有真正的理由不这样做。
你需要注意的一件事是你不能从IE窗口对象中删除属性,它会导致抛出异常。在你的情况下,因为它只是一个字符串,可能并不重要。
此失败的IE:
window.foo = 'bar';
delete window.foo;
在JavaScript的全局的问题(对任何其它语言的顶部)。是否没有解决名称冲突的机制(或者说,机制是假设它是相同的变量)。如果您使用名为currentComments
的全局变量,并且还包含一个带有currentComments
全局变量的其他模块,那么其中一个将会丢失,并且您可能会得到不可预知的结果。
这将是最好使用一个范围限定于你的模块,这样的:
(function(){
var currentComments;
function editComments() {
currentComments = $('#commentsTextBox').val();
$('#commentsTextBox').removeAttr("readonly", "readonly");
}
function cancelEditComments() {
$('#commentsTextBox').val(currentComments);
$('#commentsTextBox').attr("readonly", "readonly");
}
}());
的“removeAttr”功能只注重第一个参数。 – Pointy 2010-07-05 15:35:52
是的,这是一个错字。现在更正。 – fearofawhackplanet 2010-07-05 15:48:58