当复选框 true 或 false 时从 DOM 中删除并重新添加 [英] Remove from DOM and add back again when check box true or false

查看:20
本文介绍了当复选框 true 或 false 时从 DOM 中删除并重新添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 DOM 中删除元素,只需要在相应的复选框过滤器为真或假时再次插入.目前我没有显示或阻止,但我想完全删除元素的原因是因为我在第一个孩子上有一个特定的样式,在顶部给它更多的填充.所以目前当我更改过滤器并首先显示一个新项目时,它当前没有应用我需要的填充.

I'm trying to remove elements from the DOM only need to be inserted back in again when the corresponding checkbox filter is either true or false. currently i have display none or block, but the reason I want to remove the elements altogether is because I have a specific style on the first child giving it more padding at the top. So currently when I change the filter and a new item is displayed first it currently does not have the padding applied which I need.

小提琴:http://jsfiddle.net/amesy/kwqpf5fv/6/

上面小提琴中的代码...

The code in the fiddle above...

function StringContainsAllItems(stringVal, items){
if(items.length == 0 || items.length == null){
    return false;   
}

for(var i = 0; i < items.length; i++){
    console.log("Item: " + items[i]);
    if(stringVal.indexOf(items[i]) == -1)
    {
         return false;   
    }
}

return true;
}


$(function() { 
var $checkboxes = $("input[id^='type-']");
$('input[type=checkbox]:checked').attr('checked', false);

$checkboxes.change(function() {
    if( $('input[type=checkbox]:checked').length > 0){

        var selectorArray = [];

        $checkboxes.filter(':checked').each(function() {
            selectorArray.push($(this).attr('rel'));
            console.log($(this).attr('rel'));             
        });

        $('[data-category]').hide() // hide all rows
         .filter(function() {
             return StringContainsAllItems($(this).data('category'), selectorArray);             
        }).show(); // reduce set to matched and show

    }else
        {
         $('[data-category]').show();   
        }
});    
});

推荐答案

我不确定你是否有这个想法,但通过应用以下选择器:

I'm not sure if you had this in mind, but by applying the following selector:

$('div.portfolio-item:visible:first').addClass("first-item"); 

您可以为第一个可见 div 添加类:first-item(使用类 portfolio-item),可用于为第一个应用特殊样式分区.我在这个 answer 中发现了 :visible 选择器的用处.

You can add the class: first-item for the first visible div (with class portfolio-item), that can be used to apply special styles for the first div. I discovered the usefulness of :visible selector at this answer.

$checkboxes.change 函数中总共添加了两行代码:

Altogether, two lines of code have been added into $checkboxes.change function:

 $('div.portfolio-item').removeClass("first-item");

 $('div.portfolio-item:visible:first').addClass("first-item");

第一行只是清除之前的first-item选择.

The first line just clears the previous first-item selection.

小提琴

这篇关于当复选框 true 或 false 时从 DOM 中删除并重新添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆