当某些东西不存在时,将css添加到div中jquery

时间:2013-10-22 14:11:01

标签: jquery

我的网站上有一个有点复杂的笔记系统,通过ajax。提交新笔记时,任何人都可以选择回复或关闭它。

如果他们回复,则会在注释中附加带有回复类的div,并且回复和关闭按钮会移动到该注释。

为了保持我的风格正确,我需要能够在没有回复的情况下为按住按钮的框添加背景,但在有回复时删除该背景。

我的html看起来像这样

<div class="noteCont">
 <div class="topContainer">
  <p class="span8">
   <span>{{ $project_note->title }}</span>
  </p>
  <p class="pull-right note">date</p>
  <p class="clearfix"></p>
 </div><!--.topContainer-->
 <div class="memo">
  <p>name</p>
  <p class="noteContent"></p>
   @if($project_note->is_read)
     <p class="pull-right check">
      {{ date&nbsp;&nbsp;<i class="icon-thumbs-up"></i>&nbsp;&nbsp;<span>Read</span>
   </p>

  <div class="replyForm">
   <div class="replyButtons">
    {{ Form::open(['route'=>['note.update', $project_note->id], 'class' => 'pull-right reply_buttons']) }}
    <input type="button" class="btn btn-blue replyBtn" name="" value="Reply" />
    <input type="submit" class="btn btn-red closeBtn" name="" value="Close" />
    {{ Form::close() }}
    <p class="clearfix"></p>
  </div> <!-- .replyButtons -->

  <div class="reply">
   reply content here
  </div><!--.reply-->
</div><!--.noteCont-->

所以基本上如果单个noteCont div中没有​​回复div,则在回复表单中添加背景颜色。我该怎么做呢?任何帮助都会很精彩!

1 个答案:

答案 0 :(得分:1)

你需要遍历每个noteCont,如果有回复则添加类,如下所示:

$('.noteCont').each(function(){
  //look for replies.
  if(!($(this).find('.reply').length)){
    //there are no replies - add a background colour.
    $(this).find('.replyForm').css('background-color', 'red');
  }
});

注意:这只会添加背景颜色 - 如果您还需要删除背景颜色(例如,如果您在添加回复后再次调用此颜色),那么您需要在那里放置相应的else语句。