使用 iCheck 回调和 jquery 从列表中删除项目

Using iCheck callbacks and jquery to remove items from a list

本文关键字:列表 删除项目 jquery iCheck 回调 使用      更新时间:2023-09-26

我有一个动态列表,当用户单击某些复选框时,我正在创建该列表。 我正在使用iCheck,它内置了某些事件处理程序。 我想要的是,当用户取消选中特定复选框时,能够删除此列表的"行"之一。

这是我到目前为止所拥有的:

<script>
        $(document).ready(function(){
            var callbacks_list = $('.callbacks ul');
            $('.facebook-friends-larger input').on('ifChecked', function(event){
              callbacks_list.prepend('<li><span>#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');
            });
            $('.facebook-friends-larger input').on('ifUnchecked', function(event) {

            });
          });
</script>

.HTML:

    <ul class="facebook-friends-larger">
            <?php $offset_two=0; ?>     
            @foreach ($friends as $friend)
            <li>
            <div class="facebook_friend_large">
                <input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}">
                <label for="{{$friend}}" style="display:inline-block;">
                    <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>

<div class="callbacks">
<ul></ul>
</div>

我的问题是如何使用未检查的事件处理程序删除行? 我知道这是大致如下的:

$('#'this.id).remove();

ID 是唯一的。

但这会引发错误。 我将如何实现这一点? 谢谢。

您正在使用以下代码添加新li

.prepend('<li><span>#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');

在此事件处理程序中

$('.facebook-friends-larger input').on('ifChecked', function(event){ //... });

因此,从逻辑上讲,您可以使用以下代码删除li (IMO(,具体取决于prepend

$('.facebook-friends-larger input').on('ifUnchecked', function(event) {
    event.preventDefault();
    $('span#'+ this.id).closest('li').remove();
});

更新 :prepend更改为

.prepend('<li><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');

然后将函数中的remove行替换为此

$('.callbacks ul').find('span#'+ this.id).closest('li').remove();

另外,请确保所有id都是唯一的,两个元素不能具有相同的id