![](/img/trans.png)
[英]Jquery selector — how to select the first of specified parents of current element
[英]Select previous headings that are not parents of the current element / JQuery
我有以下標記
<div id="section1">
<h1>Titel 1</h1>
<p>Some smart Text</p>
</div>
<div id="section2">
<h2>Titel 2</h2>
<p>Some smart Text2</p>
</div>
<div id="section3-1">
<h3>Titel 3-1</h3>
</div>
<div id="section3-1content">
<ul>
<li id="section3-1content-el1">El1</li>
<li id="section3-1content-el2">El2</li>
</ul>
</div>
<div id="section3-2">
<h3>Titel 3-2</h3>
</div>
<div id="section3-2content">
<ul>
<li id="section3-2content-el1">El1</li>
<li id="section3-2content-el2">El2</li>
</ul>
</div>
當我單擊#section3-2content-el2時,我想返回
<h3>Titel 3-2</3>
(最近的h3),然后
<h2>Titel 2</h2>
接着
<h1>Titel 1</h1>.
問題在於,h3,h2和h1並不是所單擊元素的真正父對象。 有什么辦法可以返回源代碼並找到第一個h3,然后找到第一個h2,然后找到第一個h1?
問題在於:
$('#section3-2content-el1').click(function(){
$('#section3-2content-el1').parents('h3');
$('#section3-2content-el1').prevAll('h3');
$('#section3-2content-el1').closest('h3');
});
是他們都沿着dom向上走,看一看是否是h3。 但是h3不是clicked元素的父級。
有很多選擇。 考慮到您的html結構:last
是最好的選擇。 檢查演示。
$(this).parents('body').find('h3:last')
如果您的標題標簽一致,則.prev()
將是另一個選擇。
我可以通過使用jQuery的.map()
方法來返回類名的數組(或數組的排序.map()
來做到這一點。 然后,您可以將clicked元素的類名稱與共享其類名稱的標題進行匹配。
首先向<h3>
和<li>
添加一些類:
<div id="section1">
<h1>Titel 1</h1>
<p>Some smart Text</p>
</div>
<div id="section2">
<h2>Titel 2</h2>
<p>Some smart Text2</p>
</div>
<div id="section3-1">
<h3 class="first">Titel 3-1</h3>
</div>
<div id="section3-1content">
<ul>
<li id="section3-1content-el1" class="first">El1</li>
<li id="section3-1content-el2" class="first">El2</li>
</ul>
</div>
<div id="section3-2">
<h3 class="second">Titel 3-2</h3>
</div>
<div id="section3-2content">
<ul>
<li id="section3-2content-el1" class="second">El1</li>
<li id="section3-2content-el2" class="second">El2</li>
</ul>
</div>
和JS / jQuery:
$(document).ready(function(){
$('li').click(function(){
var self = $(this);
// Create an array of class names
var cls = $('h3').map(function(){
return $(this).attr('class');
});
// Loop through the array until the current iteration matches the class name of the clicked element
for (var i = 0; i < cls.length; i++) {
if (self.hasClass(cls[i])) {
// Do stuff based on whether there is a match
alert($('h3.' + cls[i]).attr('class'));
}
}
});
});
內容: http : //jsfiddle.net/KFS4E/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.