在特定元素之后获取具有特定类的下一个元素 [英] get the next element with a specific class after a specific element
问题描述
我有这样的HTML标记:
I have a HTML markup like this:
<p>
<label>Arrive</label>
<input id="from-date1" class="from-date calender" type="text" />
</p>
<p>
<label>Depart</label>
<input id="to-date1" class="to-date calender" type="text" />
</p>
<p>
<label>Arrive</label>
<input id="from-date2" class="from-date calender" type="text" />
</p>
<p>
<label>Depart</label>
<input id="to-date2" class="to-date calender" type="text" />
</p>
我希望从日期之后获取下一个元素以获得相应的日期。 (布局稍微复杂一点,但是从日期开始,从日期开始,到日期已经达到日期课程。)
I want to get the next element after from dates to get the corresponding to date. (Layout is a little more complex but from date has from-date class and to date has to-date class).
这是我想做的,我想要从日期元素中获取并使用to-date类查找dom中的下一个元素。我试过这个:
This is I am trying to do, I want to take a from date element and find the next element in the dom with to-date class. I tried this:
$('#from-date1').next('.to-date')
但它给了我空的jQuery元素。我认为这是因为 next
给出了与选择器匹配的下一个兄弟。如何获得相应的至今
?
but it is giving me empty jQuery element. I think this is because next
gives the next sibling matching the selector. How can I get the corresponding to-date
?
推荐答案
无法'找到一个直接的方法,所以为此写了一个小的递归算法。
Couldn't find a direct way of doing this, so wrote a little recursive algorithm for this.
演示: http://jsfiddle.net/sHGDP/
nextInDOM ()
函数有2个参数,即要开始查找的元素和要匹配的选择器。
nextInDOM()
function takes 2 arguments namely the element to start looking from and the selector to match.
而不是
$('#from-date1').next('.to-date')
你可以使用:
nextInDOM('.to-date', $('#from-date1'))
代码
function nextInDOM(_selector, _subject) {
var next = getNext(_subject);
while(next.length != 0) {
var found = searchFor(_selector, next);
if(found != null) return found;
next = getNext(next);
}
return null;
}
function getNext(_subject) {
if(_subject.next().length > 0) return _subject.next();
return getNext(_subject.parent());
}
function searchFor(_selector, _subject) {
if(_subject.is(_selector)) return _subject;
else {
var found = null;
_subject.children().each(function() {
found = searchFor(_selector, $(this));
if(found != null) return false;
});
return found;
}
return null; // will/should never get here
}
这篇关于在特定元素之后获取具有特定类的下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!