jQuery:查找包含特定文本的元素

3

我在页面上有一个带有事件列表的日历。当用户点击下一个或上一个按钮时,我希望用仅包含当前显示月份和年份的行的内容填充一个div。以下是这些行的结构(使用Drupal 7 Views创建)。

<div id="all-events">
  <div class="views-rows">
    <div class="field-date">
      <div class="field-content">
        <span>June 2011</span>
      </div>
    </div>
  </div>
  <div class="views-rows">
    <div class="field-event-title">
      <div class="field-content">
        <span>Some Event</span>
      </div>
    </div>
  </div>
</div>

我用jQuery做到了这一步,但是出现了很多错误:
   $('#calendar span.fc-button-next').live('click', function(){
      var month = $('#calendar .fc-header-title h2').html();
      $('.event-list').fadeOut(350, function(){
         $(this).html('');
         $('#all-events').each('.views-rows',function(){
            // Code goes here...
         });
      });
   });

我还应该提一下,我正在使用FullCalendar创建日历,因此它是使用这个插件创建的。现在我可以获取用户正在查看的当前月份,但我想浏览列表并找到包含该月份的所有行,并将它们显示在.event-list div中。

3个回答

2

我不完全理解你的要求,但是要按其文本过滤元素,请使用filter

<div>text 1</div>
<div> not this text </div>

JS

$("div").filter(function(){
   return $(this).text().indexOf("text 1") >= 0; // if contains desired text
}).html("this one matches 'text 1'");

点击这里,查看jsFiddle上的示例


当存在多个包含“text 1”的div时,它也会替换这些div,如此处所示:http://jsfiddle.net/Rd8jK/1/。 - Anderson Green

1

这看起来不对:

$('#all-events').each('.views-rows',function(){...});

这样怎么样:
$('.views-rows', '#all-events').each(function(){...});

0
自1.1.4版本以来,jQuery具有包含选择器,可选择包含特定文本的元素。
$('#calendar span.fc-button-next').live('click', function(){
  var month = $('#calendar .fc-header-title h2').html();
  $('.event-list').fadeOut(350, function(){
     var event_list = $(this).html('');
     $('#all-events .views-rows:contains(' + month + ')').each(function(){
       event_list.append($(this).html);
     });
     event_list.fadeIn();         
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接