如何选择嵌套了两个.each()函数的多个元素?
好的,正如所承诺的,这是真正的交易,首先是样本html:
-
-
-
-
-
-
-
-
我想让窗口弹出“12”,然后弹出“34” ……所以这是我的嵌套函数尝试:
var poptext = ""; $('li[data-foo=bar]').each( function () { $(this li span).each(function () { poptext = poptext + $(this).attr("id"); } alert(poptext); poptext = ""; ); } );
这似乎没有用,我认为Jquery可能会混淆多个“this”关键字? 此外,对于那些跨度开始的选择器可能存在问题。
多谢你们!
我认为你正在寻找直接后代选择器: >
像这样使用:
$('li[data-foo=bar]').each(function () { var poptext = ""; $(this).find('> ul > li > span').each(function () { poptext = poptext + $(this).attr("id"); }); alert(poptext); });
将仅选择左侧上一个表达式的直接子节点。
一个更详细但可能更易读的版本可能是:
$(this).children('ul').children('li').children('span') // selects the same
在这里看到它: http : //jsfiddle.net/xYgJg/
你的代码中有语法错误, $(this li span)
应该是$('li span', this)
你的逻辑关闭,你没有用字母ID过滤掉跨度。
这行有语法错误:
$(this li span).each(function () {
“this”是“each”循环中当前的dom元素,因此一种方法是将它包装在jQuery对象中并调用“.find()”并传入另一个选择器以获取所需的嵌套元素
获得您正在寻找的答案的逻辑也是错误的。 我不知道你到底想要找到什么,但这里有一种方法可以得到你想要的答案
var poptext = "", id; $('li[data-foo=bar]').each(function () { $(this).find('li span').each(function () { id = $(this).attr("id"); if (!isNaN(id)){ poptext = poptext + $(this).attr("id"); } }); alert(poptext); poptext = ""; });
这里有一个jsfiddle: http : //jsfiddle.net/kEjt7/1/