JQuery的父母和孩子的选择
问题描述:
我已经搜索了整个这个网站,但无法找到我的问题的答案... 可以说我有以下选择$('#me').parents().eq(2).children().eq(1).children().eq(0).children().eq(0);
我将如何能够将选定的元素变成字符串 - “乔伊”,所以我可以这样做:$(joey);
?所有元素都是div,没有class或id。JQuery的父母和孩子的选择
我想将字符串变量保存到一个数组,然后加入他们在一起,所以可以增加点击功能:
var divs=['#me','#sister','#brother'];
var divsSel=[];var divs2=[];var ds='';
$(divs).each(function(i,v){
dS=$(v).parents().eq(2).children().eq(1).children().eq(0).children().eq(0);
ds=...;\\CODE TO TURN SELECTOR INTO STRING, HERE
divsSel[i]=ds;
});
divs2=$.merge([],divsSel);
divs2.join();
$(divs2).on('click',function(){...\\It might not be joey..})
答
你可以只保存jQuery对象中的变量。你不能打电话给$(例子),但你可以把它作为例子来引用。考虑以下几点:
// Get the element and store in variable
var $example = $('.me').parent().children().eq(1).children().eq(0);
// Select the output div and write out the text of the stored jQuery obj
$('.output').text("Output = " + $example.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="child"></div>
<div class="child">
<div class="anotherchild">Example text</div>
<div class="anotherchild"></div>
</div>
<div class="me"></div>
</div>
<div class="output"></div>
答
var $joey = $('#me').parents().eq(2).children().eq(1).children().eq(0).children().eq(0);
,然后使用像 $joey.text("blabla");
答
如果我正确了,你...只是创建变量并保存元素(S)在里面。
var joey = $('#me').parents().eq(2).children().eq(1).children().eq(0).children().eq(0);
然后你不必使用转义字符,只是“joey;”
如果我正确地得到了你,你只想要(更多)更短的选择器? – Tinmar
这似乎是一个非常脆弱的结构:对你的html结构和你的JS稍作修改就会破坏。当一个类被添加到相关的祖先和相关的目标时,它可以通过$('#me')。closest('。parentClass')。find('joey')来完成,这更容易阅读,更能够应对html结构的变化... – nnnnnn