我在对话框中有一组复选框。单击按钮时会出现此对话框。这些复选框后面是带有一些文本的 anchor 标记。这些复选框符合一些有序和无序列表。
复选框的选中方式有两种情况。
- 如果单击父级,相应的子级复选框也会被选中。
- 用户也可以选择单个子项。
这里作为父项的复选框有自己的标识符。但 children 没有身份识别信息。如果它也有,那么它对于层次结构中的所有子项都有一个标识符。
我基本上需要存储在 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" />
最佳答案
我宁愿使用filter
函数:
$("a").filter(function (i, e) {
return 'Birds' === e.innerText.trim();
}).prev().attr("checked", true);
成功选中包含“Birds”的 anchor 附近的复选框。
关于javascript - 根据文本检查前面的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25794767/