我有一个这样的HTML标记:
<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>我想要获取from date之后的下一个元素,以获得对应的to date。(布局有点复杂,但from date有from-date类,to date有to-date类)。
这就是我正在尝试做的,我想要获取一个from date元素,并找到带有to-date类的dom中的下一个元素。我试过这个:
$('#from-date1').next('.to-date')但是它给了我一个空的jQuery元素。我认为这是因为next提供了与选择器匹配的下一个同级。如何获取对应的to-date
发布于 2012-07-19 20:00:37
找不到直接的方法,所以写了一个小的递归算法。
演示: http://jsfiddle.net/sHGDP/
nextInDOM()函数有两个参数,即开始查找的元素和匹配的选择器。
而不是
$('#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
}发布于 2012-07-19 19:42:46
.next('.to-date')不会返回任何内容,因为在它们之间有一个额外的p
你需要.parent().next().find('.to-date')。
如果你的dom比你的例子更复杂,你可能需要调整它。但从本质上讲,它可以归结为以下内容:
$(".from-date").each(function(){
// for each "from-date" input
console.log($(this));
// find the according "to-date" input
console.log($(this).parent().next().find(".to-date"));
});编辑:只查找ID会更好更快。下面的代码搜索所有的起始日期并获得根据日期:
function getDeparture(el){
var toId = "#to-date"+el.attr("id").replace("from-date","");
//do something with the value here
console.log($(toId).val());
}
var id = "#from-date",
i = 0;
while($(id+(++i)).length){
getDeparture($(id+i));
}看一看example。
发布于 2012-07-19 20:41:13
试一试
var flag = false;
var requiredElement = null;
$.each($("*"),function(i,obj){
if(!flag){
if($(obj).attr("id")=="from-date1"){
flag = true;
}
}
else{
if($(obj).hasClass("to-date")){
requiredElement = obj;
return false;
}
}
});https://stackoverflow.com/questions/11560028
复制相似问题