将类添加到已删除的

时间:2018-03-09 08:03:05

标签: jquery mongodb

我有一个容器类,其中有许多<div> s 当我点击一个div时,我会为其添加一个选择的类。删除一个div后,我会在其后显示下一个div的内容。

我希望将选定的类添加到其中。我怎么能这样做?

    

 var MongoClient = require('mongodb').MongoClient;
 var url = "mongodb://localhost:27017/";
 const remote = require('electron').remote;
 const main = remote.require('./index.js');
 var arr=[];
 var dict=[];
 var i=0;
var index=0;
var ed=0;
window.addEventListener("load", function () {

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("ChatBot");
  var cursor = dbo.collection("Chats").find();
  console.log(cursor);

  cursor.each(function(err,item){
    console.log(item);
    if(item!=null)
    {
      console.log(item.username+" "+item.request+" "+item.botRp);
      arr.push(item.username);
      dict.push({
        key:   item.username,
        user: item.request,
        bot : item.botRp
  });
     

    }
  });
});
myLoop();


}, false);

  function myLoop () {           //  create a loop function
  setTimeout(function () {
 if(ed==0)
 {
  $('#foo').append('<div class="ruser" style="margin-top:1em;">'+
  				'<div class="rname z-depth-2 hoverable">'+
  					'<h5>'+arr[i]+'</h5>'+
  				'</div>'+
  				'<input type="checkbox" class="check" id="test'+(i+1)+'"  />'+
        '<label for="test'+(i+1)+'" class="checkl" style="display:none"></label>'+
  			'</div>');
        ed++;
  }
  else {
    $('#foo').append('<div class="ruser">'+
    				'<div class="rname z-depth-2 hoverable">'+
    					'<h5>'+arr[i]+'</h5>'+
    				'</div>'+
    				'<input type="checkbox" class="check" id="test'+(i+1)+'"  />'+
          '<label for="test'+(i+1)+'" class="checkl" style="display:none"></label>'+
    			'</div>');

  }
  if((i+1)==1)
  {
      $('#disp').html('You have '+(i+1)+" new message");
  }
  else{
    $('#disp').html('You have '+(i+1)+" new messages");
  }

  i++;                   //  increment the counter
  if (i < arr.length) {            //  if the counter < 10, call the loop function
     myLoop();             //  ..  again which will trigger another
  }                        //  ..  setTimeout()
   }, 1200);
}
 $(document).on('click', '.rname', function() {
  console.log('clicked');
  $('.rname').removeClass('selected');
  $(this).addClass('selected');
 $('.NoView').fadeOut();
 $('#chat').empty();
 var name = $(this).closest('div').eq(0).find("h5").text();
 var userRequest="";
 var botRep ="";
 for(var j=0;j<dict.length;j++)
 {
  if(dict[j].key==name)
  {
    console.log("found");
    userRequest=dict[j].user;
    botRep=dict[j].bot;
    index=j;
    break;
  }
 }
          $('#chat').append('<div class="BotWrapper">' +
            '<div class = "speech-bubble z-depth-5"><p>' + userRequest + '</p></div><div class=""></div>');
            $('#chat').append('<div class="BotWrapper">' +
                '<div class = "speech-bubble z-depth-5"><p>' + botRep + '</p></div><div class=""></div>');


  $('.medium').fadeIn();
  $('.small').fadeIn();
 });
$('#del').click(function() {
   console.log('delete');
   $(".check:checked").each(function() {
    var k=0;
    var name = $(this).closest('div').eq(0).find("h5").text();
    console.log(name+" hkhbhjjkh");
    for(var i = 0; i < dict.length; i++) {
      console.log(dict[i].key+" "+name);
       if(dict[i].key == name) {
        k=i;
        console.log('hg');
        dict.splice(i, 1);
        break;
      }
 }
 console.log(dict);
if(index==k)
{
  $('#chat').empty();
  $('#chat').append('<div class="BotWrapper">' +
      '<div class = "speech-bubble z-depth-5"><p>' + dict[k].user + '</p></div><div class=""></div>');
      $('#chat').append('<div class="BotWrapper">' +
          '<div class = "speech-bubble z-depth-5"><p>' + dict[k].bot + '</p></div><div class=""></div>');
}
   $(this).closest('div').eq(0).fadeOut();
   $('.rname').eq(k).addClass('selected');
});

 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-item large z-depth-5">
  <div class="participants z-depth-5">
    <h4>Requests</h4>
  </div>
  <div class="Users" id="foo">
    <div class="edit">
      <button>
  			<i class="material-icons right" id="del">delete</i>
  			</button>
      <button>
  			<i class="material-icons right waves-light " id="edit">edit</i>
  			</button>
    </div>
  </div>
</div>

这是图像。截至目前,DKe1kor在删除之后被选中,我想要下一个div,即Oah1kor,以获得这样的CSS。

Image

1 个答案:

答案 0 :(得分:1)

首先,您尝试将jQuery函数应用于本机HTMLElement:

$('.rname')[0].addClass(…

哪个自然不行。要将addClass函数应用于jQuery集合中的第一个项,您需要使用eq()函数而不是方括号表示法:

$('.rname').eq(0).addClass(…

要真正解决您的问题,您应该直接使用已经勾选的DOM元素的引用来访问下一个符合条件的元素(以应用&#34;选择&#34;类)。您可以在淡入淡出效果完成后立即轻松完成此操作:

    // …
    $(this).closest('div').fadeOut(300, function() {
      let $t = $(this);
      // Add selected class to eligible element
      // $t.next().addClass('selected').end().remove();
      // if you would like to set the previous element as selected
      // in case last item was clicked, replace the previous line with:
      $t[$t.next().length ? 'next':'prev']().addClass('selected').end().remove();
    });

这是一个演示,可以查看工作中的代码 为简单起见,此代码段假定某些项已加载到DOM中:

&#13;
&#13;
var dict = [
    {key: '1rst item', user: 'First user', bot: 'bot 1'}
    , {key: '2nd item', user: 'Second user', bot: 'bot 2'}
    , {key: '3rd item', user: 'Third user', bot: 'bot 3'}
], index = 0;

$(document).on('click', function (e) {
  var $t = $(e.target);
  if ($t.is('.ruser')) {
      // Unselect '.selected' element
      $t.parent().children('.ruser').removeClass('selected');
      // Select current element
      $t.addClass('selected');
      // Save index
      index = dict.map((el, i) => {
         return el.key == $t.find('h5').text() ? i : null
      }).filter(x=>x!==null)[0];
      $('h4').html(`Requests <small>(Index is now equal to ${index})</small>`);
  }
});

$('#del').click(function() {
  $(".check:checked").each(function() {
    var name = $(this).closest('div').eq(0).find("h5").text()
        , $chat = $('#chat')
        , k = 0
        ;
    for (var i = 0; i < dict.length; i++) {
      if (dict[i].key == name) {
        k = i;
        dict.splice(i, 1);
        break;
      }
    }
    if (index == k && dict[k]) {
      console.log('Selected item is being deleted.');
      [dict[k].user, dict[k].bot].forEach(el => {
        $chat.append(`
          <div class="BotWrapper">
              <div class="speech-bubble z-depth-5">
                  <p>${el}</p>
              </div>
          </div>
        `);
      });
    }
    $(this).closest('div').fadeOut(300, function() {
      let $ruser = $(this)
      // Determine which will be the element eligible to 'selected' class
        , $next = $ruser.next()
        , $all = $ruser.parent().find('.ruser');
      // Deleting last make first item eligible
      !$next.length && ($next = $all.eq(0));
      $ruser.remove();
      // DO NOT REPEAT YOURSELF: "selected" class handling belongs to the click event handler above.
      // Code elsewhere should not interfer with it (Making so would harden
      // debbuging application state). So we need to trigger the click event
      // so that related actions are correctly executed 
      // (Updating "index" variable for instance).
      $(document).triggerHandler({type:'click', target: $next[0]});
    });
  });
});
&#13;
.selected{color: red}

.BotWrapper, .BotWrapper * {display: inline-block}
.BotWrapper * + * {margin-left: 10px}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-item large z-depth-5">
    <div class="participants z-depth-5">
        <h4>Requests</h4>
    </div>
    <div class="Users" id="foo">
        <div class="edit">
            <button id="del">
                <i class="material-icons right">delete</i>
                </button>
            <button>
                <i class="material-icons right waves-light " id="edit">edit</i>
                </button>
        </div>
        
        <!--
           Let say 3 items have already been loaded
        -->
        <div class="ruser selected">
          <div class="rname z-depth-2 hoverable">
            <h5>1rst item</h5>
          </div>
          <input type="checkbox" class="check" id="test0"  />
          <label for="test0" class="checkl" style="display:none"></label>
        </div> 
        <div class="ruser">
          <div class="rname z-depth-2 hoverable">
            <h5>2nd item</h5>
          </div>
          <input type="checkbox" class="check" id="test1"  />
          <label for="test1" class="checkl" style="display:none"></label>
        </div>
        <div class="ruser">
          <div class="rname z-depth-2 hoverable">
            <h5>3rd item</h5>
          </div>
          <input type="checkbox" class="check" id="test3"  />
          <label for="test3" class="checkl" style="display:none"></label>
        </div>       
        
    </div>
</div>
<div id="chat"></div>
&#13;
&#13;
&#13;