在全局Javascript变量中保存临时表单信息
是否有任何理由不应该执行以下操作(以避免使用隐藏字段存储临时信息)?为了简洁起见,我使用jQuery语法,但这是一个一般的JavaScript问题在全局Javascript变量中保存临时表单信息,javascript,jquery,global-variables,Javascript,Jquery,Global Variables,是否有任何理由不应该执行以下操作(以避免使用隐藏字段存储临时信息)?为了简洁起见,我使用jQuery语法,但这是一个一般的JavaScript问题 function editComments() { window.currentComments = $('#commentsTextBox').val(); $('#commentsTextBox').removeAttr("readonly"); } function cancelEditComments() { $('
function editComments() {
window.currentComments = $('#commentsTextBox').val();
$('#commentsTextBox').removeAttr("readonly");
}
function cancelEditComments() {
$('#commentsTextBox').val(window.currentComments);
$('#commentsTextBox').attr("readonly", "readonly");
}
我知道一般认为全球化是一种不好的做法,但这样做真的有问题吗
除非您能给出原因/解释,否则请不要回答/评论“全局变量是邪恶的” 除了全局变量是邪恶的之外,这没有什么真正的问题 但是,如果您仍在使用jQuery,在我看来,更好的方法是使用以下命令将其存储在元素中:
只要您将其保存在脚本中,并且对元素不做任何其他操作,就应该可以正常工作。如果忽略“全局变量是坏的”参数,就没有真正的理由不这样做 你需要注意的一件事是你不能删除IE中窗口对象的属性,它会引发异常。在您的情况下,因为它只是一个字符串,所以可能不重要 这在IE上失败:
window.foo = 'bar';
delete window.foo;
javascript中globals的问题(在任何其他语言的问题之上)。没有解决名称冲突的机制(或者更确切地说,该机制只是假设它是同一个变量)。如果您使用一个名为
currentComments
的全局变量,并且还包括其他一些带有currentComments
全局变量的模块,那么其中一个变量将丢失,您可能会得到不可预测的结果
最好使用一个适用于您的模块,因此:
(function(){
var currentComments;
function editComments() {
currentComments = $('#commentsTextBox').val();
$('#commentsTextBox').removeAttr("readonly", "readonly");
}
function cancelEditComments() {
$('#commentsTextBox').val(currentComments);
$('#commentsTextBox').attr("readonly", "readonly");
}
}());
“removeAttr”函数只关注第一个参数。是的,这是一个输入错误。现在更正。
jQuery.data()
()的jQuery文档说这是一种“低级方法”,您应该使用.data()
。你知道那是什么意思,为什么吗?@Lèse很好,谢谢你!我更正了代码。“高级”.data(key,value)
是$(element)
对象的直接方法(而不是jQuery.data(elementname,key,value)
)
(function(){
var currentComments;
function editComments() {
currentComments = $('#commentsTextBox').val();
$('#commentsTextBox').removeAttr("readonly", "readonly");
}
function cancelEditComments() {
$('#commentsTextBox').val(currentComments);
$('#commentsTextBox').attr("readonly", "readonly");
}
}());