我无法理解为什么我的选择器不能用于foreach循环。
我的DOM看起来像这样:
var returnVal = new List<Group>();
if (IsUserInRole("Admin"))
{
returnVal.AddRange(groupsByMembersFirst);
}
if (IsUserInRole("B"))
{
returnVal.AddRange(groupsByMembersFirst.Where(g => g.GroupTypeName != "Bikes"));
}
if (IsUserInRole("C"))
{
returnVal.AddRange(groupsByMembersFirst.Where(g => g.GroupTypeName != "Cars"));
}
if (IsUserInRole("N"))
{
returnVal.AddRange(groupsByMembersFirst.Where(g => g.GroupTypeName != "NanoCars"));
}
return returnVal;
有人会解释为什么以下选择器对foreach迭代无效吗?
<div id="page1" class="ui-droppable">
<div class="ui-draggable ui-draggable-handle ui-draggable-dragging signatureInstance selected btn-delete" style="position: absolute; left: 185px; top: 470px;">
<img src="http://example.com/img/field.png">
<span class="glyphicon glyphicon-remove btn-delete"><span></span></span>
</div>
<div class="ui-draggable ui-draggable-handle ui-draggable-dragging signatureInstance selected btn-delete" style="position: absolute; left: 171px; top: 562px;">
<img src="http://example.com/img/field.png">
<span class="glyphicon glyphicon-remove btn-delete"><span></span></span>
</div>
</div>
或
$('#page1 .signatureInstance').forEach(function(index) {
console.log($(this));
});
甚至:
$('#page1 .ui-draggable .ui-draggable-handle .ui-draggable-dragging signatureInstance .selected .btn-delete').forEach(function(index) {
console.log($(this));
});
答案 0 :(得分:2)
你需要使用 each()
来迭代jQuery对象,它是为它构建的。
.each()方法旨在使DOM循环结构简洁且不易出错。调用时,它会迭代属于jQuery对象的DOM元素。每次回调运行时,都会从0开始传递当前循环迭代。更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字this指的是元素。 (摘自https://api.jquery.com/each/)
Array.prototype.forEach()
用于迭代数组而不是用于jQuery对象集合。
$('#page1 .signatureInstance').each(function(index) {
console.log($(this));
});