【发布时间】:2014-11-05 20:02:00
【问题描述】:
我在一个对话框中有一组复选框。单击按钮会出现此对话框。这些复选框后跟带有一些文本的锚标记。这些复选框是按照一些有序和无序列表的。
checkbox的方式有两种情况。
- 如果单击父级,则相应的子级复选框也会被选中。
- 用户也可以选择单个孩子。
这里作为父母的复选框有自己的标识符。但是孩子们没有标识符。如果它也具有层次结构中所有子级的单一标识符。
我需要基本上存储在 localStorage 中选中的复选框,以便在重新加载页面时我可以检索之前选中的复选框的状态。
上面的第一种情况发生并且工作正常,但在第二种情况下,我无法检索单个复选框的先前状态。我尝试在检查到 localStorage 的复选框之后发送文本,然后在页面加载时将每个文本与存储的值进行比较。如果匹配,则检查文本前一个元素的属性。这是我应用的逻辑。但它不能正常工作。
这是我的代码
function display(){
//some code to display dialog box where the checkboxes along with anchor tags come into picture
var vals[];
$("input[type=checkbox").each(function(){
vals.push($(this).next("a").text());
});
//some code which brings in localStorage and the existing data in the dialog
代码继续进行,最终将所有参数输入并检查以下条件。
if ( z[x]==hname[k]){
alert("Matched");
$('a[text="'+hname[k]+'"}').prev().attr("checked",true);
}
这里 z[x] 是我之前存储在 localStorage 中的值,hname[k] 是对话框中的所有值。
现在我的问题在于这一行。
$('a[text="'+hname[k]+'"]').prev().attr("checked",true);
我正在尝试检查文本之前的元素。但它不起作用。
我的html代码::
<ul class="test_ex">
<li>
<input type="checkbox" id="chckBox" class="parent" /> <a class="ref">Fruits</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Apple </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Orange </a>
</li>
</ul>
<ul class="test_ex_sample">
<li>
<input type="checkbox" id="chckBox" class="parent" /> <a class="ref">Birds</a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref"> Peacock </a>
</li>
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref">Parrot </a>
</li>
</ul>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="parent" /> <a class="ref"> Food </a>
<ul class="example">
<li>
<input type="checkbox" id="chckBox" class="child" /> <a class="ref">Bread </a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<input type="button" id="testB" value="OK" />
【问题讨论】:
-
把HTML代码贴出来会更好。
-
我添加了一个类似的 HTML,我在 SO 上找到了 :)
-
text="..."不是有效的 HTML 属性,并且它不出现在您提供的 HTML 中。 -
我会将其更改为值。还是不行。
标签: javascript jquery html checkbox local-storage