2016-02-13 140 views
0

我已經搜索了整個這個網站,但無法找到我的問題的答案... 可以說我有以下選擇$('#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..}) 
+0

如果我正確地得到了你,你只想要(更多)更短的選擇器? – Tinmar

+1

這似乎是一個非常脆弱的結構:對你的html結構和你的JS稍作修改就會破壞。當一個類被添加到相關的祖先和相關的目標時,它可以通過$('#me')。closest('。parentClass')。find('joey')來完成,這更容易閱讀,更能夠應對html結構的變化... – nnnnnn

回答

0

你可以只保存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>

0

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

,然後使用像 $joey.text("blabla");

0

如果我正確了,你...只是創建變量並保存元素(S)在裏面。

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

然後你不必使用轉義字符,只是「joey;」