Javascript 数据仅提取数组的第一项,该数组放入使用 iCheck 复选框输入的数据名称字段中


Javascript data only pulling the first item of an array that is put in data-name field of a checkbox input with iCheck

我正在使用iCheck插件在选中复选框时打印出一些回调数据。 我有两个数组,一个带有 id,另一个带有名称。 它们在数组中的位置同步(array1[0] = 1, array2[0] = greg, 1->greg etc...(

我正在尝试提取与每个复选框关联的 id 和名称。 这是我所拥有的(带有 id 的数组是$friend的,带有名称的数组是 $friend_names:

<ul class="facebook-friends-larger">
        <?php $offset_two=0; ?>     
        @foreach ($friends as $friend)
        <li>
        <div class="facebook_friend_large">
            <input tabindex="1" type="checkbox" data-name="{{$friend_names[$offset_two]}}" name="friend[]" id="{{$friend}}" value="{{$friend}}" style="display:inline-block;">
            <label for="{{$friend}}">
                <span class="icon"><a href="http://www.facebook.com/{{ $friend }}"><img src="https://graph.facebook.com/{{ $friend }}/picture" alt="" height="50" width="50"></a></span>
                <span class="icon_text_large"><a href="http://www.facebook.com/{{ $friend }}"><?php echo $friend_names[$offset_two]; ?></a></span>
            </label>
        </div>
        </li>
        <?php $offset_two++; ?>                 
        @endforeach
        </ul>

Javascript部分:

<div class="callbacks">
<ul></ul>
</div>
<script>
        $(document).ready(function(){
            var callbacks_list = $('.callbacks ul');
            $('.facebook-friends-larger input').on('ifChecked', function(event){
                var name = $('.facebook-friends-larger input').data('name'); 
                callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + name + '</li>');

            });
            $('.facebook-friends-larger input').on('ifUnchecked', function(event) {
                callbacks_list.find('span#'+ this.id).closest('li').remove();
                console.log(this.id);
            });
          });
        </script>

当我运行它并开始选中框时。 与复选框关联的 ID 与正确关联的复选框一起正确打印出来。 但是,我创建的"name"变量仅打印出每个复选框的"$friend_names"数组中的名字。 您知道为什么没有为每个复选框更新 name 变量吗? 谢谢。

您需要

更改代码以使用 this 引用选中的项目(不是所有项目(,如下所示:

   $(document).ready(function(){
        var callbacks_list = $('.callbacks ul');
        $('.facebook-friends-larger input').on('ifChecked', function(event){
            // get the name for only the checked item
            var name = $(this).data('name'); 
            callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + name + '</li>');

        });
        $('.facebook-friends-larger input').on('ifUnchecked', function(event) {
            // remove parent li
            $(this).closest('li').remove();
            console.log(this.id);
        });
      });

我还通过使用 this 简化了取消选中功能。