无法在委托事件处理程序中选择第二个动态div

时间:2018-06-12 14:37:15

标签: jquery jquery-selectors

我希望在点击chat-tab时更改有效标签和会议室的类别。我们希望从hidden中删除未被点击的room类,并将其添加到不相关的div中。

问题在于,无论我尝试什么,我都无法让房间的选择器工作。



$('.chat-container').on('click', '.chat-tab', (function() {
  activeTab = $('body').data('activeTab');


  //working fine
  $('.chat-tab').removeClass("active");
  $('.chat-tab[data-tab="' + activeTab + '"]').addClass("active");

  var newActiveTab = $(this).attr("data-tab");
  $('body').data('activeTab', newActiveTab);

  //Do not work
  $('.rooms div[id!=' + newActiveTab + '_room]').addClass("hidden");
  $('.rooms div[id=' + newActiveTab + '_room]').removeClass("hidden");

}));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chat-container">
  <!--dynamic tabs-->
  <ul class="nav nav-tabs" id="chat-bar">
    <li class="chat-tab room-tab active" data-tab="Public"><a data-toggle="pill">Public</a></li>
    <li class="chat-tab" data-tab="Sports"><a data-toggle="pill">Sports</a></li>
  </ul>
  <!--/tabs-->

  <!--dynamic rooms-->
  <div class="rooms">
    <div id="Public_room" class="room hidden">
      <ol id="Public_msgOl" >
        <li>dodo : Hi Pubilc</li>
      </ol>
    </div>

  <div id="Sports_room" class="room hidden">
    <ol id="Sports_msgOl" >
      <li>dodo : Whats up sportsmen?</li>
    </ol>
  </div>
</div>
<!--/rooms-->
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我不确定你的情况是否属实,但找到activeTab的名字并不适合我。然而真正的问题是你的聊天室选择器。当您查询ID时,您必须用引号将值括起来,例如[id="value"]

&#13;
&#13;
$('.chat-container').on('click', '.chat-tab', function() {
  activeTab = $("ul .active").attr("data-tab");

  //working fine
  $('.chat-tab').removeClass("active");
  $('.chat-tab[data-tab="' + activeTab + '"]').addClass("active");

  var newActiveTab = $("ul .active").attr("data-tab");
  $('body').data('activeTab', newActiveTab);

  //Do work now
  $(".rooms div[id!='" + newActiveTab + "_room']").addClass("hidden");
  $(".rooms div[id='" + newActiveTab + "_room']").removeClass("hidden");
  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="chat-container">
  <!--dynamic tabs-->
  <ul class="nav nav-tabs" id="chat-bar">
    <li class="chat-tab room-tab active" data-tab="Public"><a data-toggle="pill">Public</a></li>
    <li class="chat-tab" data-tab="Sports"><a data-toggle="pill">Sports</a></li>
  </ul>
  <!--/tabs-->

  <!--dynamic rooms-->
  <div class="rooms">
    <div id="Public_room" class="room hidden" data-pane="Public">
      <ol id="Public_msgOl" class="chat__messages">
        <li><strong class="msg">dodo : </strong>Hi there!</li>
      </ol>
    </div>

  <div id="Sports_room" class="room" data-pane="Sports">
    <ol id="Public_msgOl" class="chat__messages">
      <li><strong class="msg">dodo : </strong>Whats up?</li>
    </ol>
  </div>
</div>
<!--/rooms-->
</div>
&#13;
&#13;
&#13;