2012-01-27 59 views
2

如何从插件被调用的集合(不是DOM本身)中移除没有id属性的元素?从jQuery选择中删除没有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); 

回答

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/

+0

辉煌。据我了解,这只会筛选选择而不会影响DOM或可链接性,对吗? – gremo 2012-01-27 14:29:17

+0

@Gremo是的,只有'valid'变量将包含元素的过滤列表。 – 2012-01-27 14:55:52

+0

这很好,但过滤器函数应该返回有效的元素(因此返回this.id)...因为jsfiddle显示红色的无效元素;) – gremo 2012-01-27 15:03:04

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

请问这种突破chainability?我的意思是我想循环选择的每个有效元素,但不从DOM本身移除元素。 – gremo 2012-01-27 14:19:52

+0

你只需要检查是否(!$(“some element”)。prop(“id”)){than do something} – 2012-01-27 14:22:02

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

我想这会从集合和DOM中删除,对吗? – gremo 2012-01-27 14:22:24

+1

看起来这个问题自编辑以来,我将编辑我的答案以匹配现在。 – epascarello 2012-01-27 22:18:19