JQuery父子选择器

时间:2016-02-13 22:47:07

标签: jquery jquery-selectors parent-child

我在这个网站上搜索和搜索,但无法找到我的问题的答案...... 假设我有以下选择器$('#me').parents().eq(2).children().eq(1).children().eq(0).children().eq(0);我如何能够将所选元素转换为字符串 - " joey"所以我可以这样做:$(joey);?所有元素都是div,没有一个是class'或者是id。

我想将字符串变量保存到数组中,然后将它们连接在一起,这样我就可以添加一个单击函数:

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..})

3 个答案:

答案 0 :(得分:0)

您可以将jQuery对象存储在变量中。您无法调用$(示例),但您可以将其作为$ example引用。请考虑以下事项:



// 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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var $joey = $('#me').parents().eq(2).children().eq(1).children().eq(0).children().eq(0);

然后使用喜欢 $joey.text("blabla");

答案 2 :(得分:0)

如果我找到你的话......只需创建变量并将其保存在其中。

var joey = $('#me').parents().eq(2).children().eq(1).children().eq(0).children().eq(0);

然后你不必使用转义字符,只需“joey;”