2012-01-27 61 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