从jQuery选择中删除没有id的元素?

时间:2012-01-27 14:12:56

标签: jquery jquery-plugins jquery-selectors

如何从调用插件的集合(而不是DOM本身)中删除没有id属性的元素?

<span id="id737293" class="attach"></span>
<div class="attach"></span>

jQuery调用和插件:

$('.attach').attach();

(function($) {

    $.fn.attach = function(options) {
       // Remove elements (without id) on which the plugin was invoked
       var valid = ???;

       // Loop each valid element (with id attribute) and process
       valid.each(function() {
       });

       return this; // Maintain chainability
    };

})(jQuery);

3 个答案:

答案 0 :(得分:5)

使用.filter删除没有ID的元素。

(function($) {

    $.fn.attach = function(options) {
       // Remove elements (without id) on which the plugin was invoked
       var valid = this.filter(function() { return !!this.id; });

       // Loop each valid element (with id attribute) and process
       valid.each(function() {               
       });

       return this; // Maintain chainability
    };

})(jQuery);

$('.attach').attach();

http://jsfiddle.net/5Kn9W/2/

var valid = this.not(':not([id])'); - http://jsfiddle.net/5Kn9W/1/

答案 1 :(得分:1)

 if(!$(elem).prop("id")){
   $(this).remove()
}

答案 2 :(得分:1)

var elementsWithClassAttachAndHasId = jQuery(".attach:has([id])");
var elementsWithClassAttachAndNoId = jQuery(".attach:not([id])");