繁体   English   中英

不正确的数组推送和拼接?

[英]incorrect array push and splice?

我正在创建一个邀请系统。 我正在使用ajax加载搜索结果列表。 单击li时,我将用户ID推入数组,并在li上附加一个对勾标记,以使他们知道他们已添加到列表中。

  1. 推送有效,但拼接无效。 同样,当列表为空时,提交按钮不会返回其禁用状态和原始样式。

最后,当我再次搜索(重新调用ajax)时,它会删除附加的选中标记。 使用javascript是否可以存储单击哪个用户并在他们搜索其他名称时保留附加的选中标记?

(^当我用ajax加载结果时,我检查是否有人在我的数据库中被邀请,因此我可以这样做,如果他们已经被邀请,则单击将从表中删除..如果不在li上单击,我用ajax插入并setTimeout成功。.您认为这是不好的做法吗?)

以下是我的html &&脚本

HTML
<li class='inviteUser'>
    <img src='$usersProfilePhoto' alt=''>
    <h2>$usersname</h2>
    <input type='hidden' value='$otherUserID'>
    <span></span>
</li>


$(function(){

    var inviteList = new Array();

      $(document).on('click', '.inviteUser', function(){

          var inviteUserID = $(this).children('input').val();

          inviteList.push(inviteUserID)

          $(this).children('span').append("<p class='remove'>&#x2713;</p>");

          if(inviteList.length > 0) {

              document.getElementById('imcSubmitButton').disabled = false;
              $('#imcSubmitButton').css({'opacity':'1'});

          } else {

              document.getElementById('imcSubmitButton').disabled = true;
              $('#imcSubmitButton').css({'opacity':'0.25'});
          }

      });

      $(document).on('click', '.remove', function() {

          inviteList.splice($(this).index(), 1);

          $(this).remove();

      });

});

问题在于inviteList中的索引与HTML中的索引不对应。 您应该在inviteList中搜索包含该项目的userID的元素,然后将其拼接出来。

  $(document).on('click', '.remove', function() {
      var userid = $(this).parent().siblings("input").val();
      var index = inviteList.indexOf(userid);
      if (index != -1) {
        inviteList.splice(index, 1);
      }
      $(this).remove();
  });

为了通过记住邀请哪些用户来解决您的问题,处理AJAX响应者的代码可以使用:

if (inviteList.indexOf(userId) != -1) {
    // Add checkmark
}

如果inviteList是一个对象,而不是使用用户inviteList作为键的数组,那么事情会更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM