在特定元素之后获取具有特定类的下一个元素

我有这样的HTML标记:

我希望从日期之后获取下一个元素以获得相应的日期。 (布局稍微复杂一点,但是从日期开始,从日期开始,到日期已经到了日期类)。

这是我想要做的,我想从date元素中获取并使用to-date类在dom中找到下一个元素。 我试过这个:

 $('#from-date1').next('.to-date') 

但它给了我空的jQuery元素。 我认为这是因为next给出了与选择器匹配的下一个兄弟。 我怎样才能获得相应to-date

无法找到这样做的直接方法,所以为此编写了一个小的递归算法。

演示: http //jsfiddle.net/sHGDP/

nextInDOM()函数接受2个参数,即从中开始查找的元素和要匹配的选择器。

代替

 $('#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 } 

.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就会好得多,速度也快。 以下代码搜索所有from-dates并获取根据日期:

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

看看这个例子 。

尝试

 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; } } }); 
  var item_html = document.getElementById('from-date1'); var str_number = item_html.attributes.getNamedItem("id").value; // Get id's value. var data_number = showIntFromString(str_number); // Get to-date this class // Select by JQ. $('.to-date'+data_number) console.log('to-date'+data_number); function showIntFromString(text){ var num_g = text.match(/\d+/); if(num_g != null){ console.log("Your number:"+num_g[0]); var num = num_g[0]; return num; }else{ return; } } 

使用JS。 从你的身份证中获取密钥号码。 分析它比输出数字。 使用JQ。 选择组合字符串与你想要的比+这个数字。 希望这也可以帮到你。