更正函数的jQuery结构,该函数应在DOM就绪状态下运行,并在整个浏览会话中运行



我的网站包含单选按钮和复选框。

当用户在表单中选择一个并提交它时,会存储此状态,这样当用户返回到页面时,它会按照用户以前的选择加载。

其中一些复选框具有子元素,当选中它们的父元素时,会更改其禁用属性,以便与它们交互。

我使用jQuery函数来实现这一点。

如果用户以前选择了禁用子元素的父元素,当他们返回页面时,我需要启用子元素的功能。

我还需要在每次用户在浏览会话中选择一个时运行此功能。

我目前能够通过复制我的jQuery函数来实现这一点,一次是在WhenDOMReady封装中,一次没有。

我怀疑这是一种糟糕的做法,我是对的吗?如果是,我该怎么做?

为了说明我的观点,举一个例子:

//First the code for DOM ready:
//You can see it disables and unchecks boxes if they are not checked etc.
$(function() {
if ($('#parent').is(':checked')) {
$('#child1').removeAttr('disabled');
$('#child2').removeAttr('disabled');
} else {
$('#child1').attr('disabled', true);
$('#child1').removeAttr('checked');
$('#child2').attr('disabled', true);
$('#child2').removeAttr('checked');
}  
});
//Now, the exact same function just without the DOM ready encapsulation.
if ($('#parent').is(':checked')) {
$('#child1').removeAttr('disabled');
$('#child2').removeAttr('disabled');
} else {
$('#child1').attr('disabled', true);
$('#child1').removeAttr('checked');
$('#child2').attr('disabled', true);
$('#child2').removeAttr('checked');
}  

谢谢你的建议。

所以基本上您希望页面的状态保持不变?

您可以将状态存储在几个位置:

  1. 客户端存储
  2. Cookie
  3. URL哈希

Cookies可能是最简单的。

为了正确地保持状态,您必须跟踪实际状态。因此,每当DOM的状态发生更改时,都要存储更改。然后,当用户打开页面时,查看cookie并恢复状态(这是DOM就绪部分)。

这并不总是一件容易的事情,因为状态可能非常复杂。假设你有一个某种可折叠的树,你需要跟踪哪些节点被扩展了。

如果你只是想跟踪一些复选框,应该不会太难。

是的,重复这样的代码是不好的做法。所以,如果你的代码做了它应该做的,你可以把它写下来。

我相信您使用的CMS在Ajax框架中执行一些表单Ajax任务,对吧?(例如Drupal?)否则我无法想象为什么这个代码会像你描述的那样。

(function($) { 
var init = function() {
if ($('#parent').is(':checked')) {
$('#child1').removeAttr('disabled');
$('#child2').removeAttr('disabled');
} else {
$('#child1').attr('disabled', true);
$('#child1').removeAttr('checked');
$('#child2').attr('disabled', true);
$('#child2').removeAttr('checked');
}  
}
//first call
init();
//second call
$(function() {
init();
});
})(jQuery);

最新更新