例如,我有以下div类
<div class="info_title">title 1</div>
<div class="info_message">message 1</div>
<div class="info_title">title 2</div>
<div class="info_message">message 2</div>
<div class="info_title">title 3</div>
<div class="info_message">message 3</div>
我想遍历每个 info_title 类并显示其文本。但是我也想在同一循环中使用 info_message 类显示相应div的文本。下面的代码是我试图做到的方式。
if ($(".info_title").length) {
$( ".info_title" ).each(function( i ) {
alert($( this ).text());
// alert('info message');
});
}
我该怎么做呢?
答案 0 :(得分:0)
这很不稳定,因为它取决于您当前的结构,但是您可以尝试prev,它可以让您在DOM中所选元素的之前立即选择元素:
$('.info_messages').each(function(i, ele) {
var $msg = $(ele);
alert($msg.text()); //.info_messages text
var $title = $msg.prev('.info_title');
if ($title.length) { //Only alert title text if it exists
alert($title.text()); //.info_title text
}
});