按属性条件删除某些div

Remove certain divs by attributes conditions

我有这样的东西

<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>

如何删除 "data-count" 属性值小于 15 的 div?

请试试这个:

$('div').each(function() {
    if ( $(this).attr('data-count') < 15 ) {
        $(this).remove();
    }
});

DEMO

这可能不是最有效的方法,但它有效:

function removeLowData() {
    for(var i = 1; i < 15; i++) {
        var elements = $("[data-count='" + i + "']");
        for(var j = 0; j < elements.length; j++) {
            $(elements[j]).remove(); 
           //or use .hide() if you still want them to be part of the dom but not visible
        }
    }
}

每当您需要删除 div 时,只需调用 removeLowData()

这样效率更高,因为它只选择具有data-count属性的divs,并且只为每个元素构造一次jQuery对象:

$('div[data-count]').each(function () {
    var $this = $(this);

    if ($this.attr('data-count') < 15) {
        $this.remove();
    }
});

演示:

$('button').on('click', function () {
    $('div[data-count]').each(function () {
        var $this = $(this);

        if ($this.attr('data-count') < 15) {
            $this.remove();
        }
    });
});
div[data-count]:before {
    content: "<div data-count=\"" attr(data-count) "\">";
}

div[data-count]:after {
    content: "</div>";
}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<button type="button">Remove data-count less than 15</button>
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>

原生的替代解决方案JavaScript:

var divs = document.querySelectorAll('div[data-count]'),
    div, i;

for (i = 0; i < divs.length; i++) {
    div = divs[i];
    if (div.getAttribute('data-count') < 15) {
        // this will not affect iteration because querySelectorAll is a non-live NodeList
        div.parentNode.removeChild(div);
    }
}

演示:

var button = document.querySelector('button');

button.addEventListener('click', function () {
    var divs = document.querySelectorAll('div[data-count]'),
        div, i;

    for (i = 0; i < divs.length; i++) {
        div = divs[i];
        if (div.getAttribute('data-count') < 15) {
            // this will not affect iteration because querySelectorAll is a non-live NodeList
            div.parentNode.removeChild(div);
        }
    }
});
div[data-count]:before {
    content: "<div data-count=\"" attr(data-count) "\">";
}

div[data-count]:after {
    content: "</div>";
}
<button type="button">Remove data-count less than 15</button>
<div data-count="5">Something</div>
<div data-count="10">Something</div>
<div data-count="15">Something</div>
<div data-count="20">Something</div>
<div data-count="25">Something</div>