从插件中删除jQuery对象中的元素
remove elements from the jQuery object from within a plugin
我认为我在这里弄错了一些基本原理,因为我认为这应该有效。我正在尝试通过匹配集的子p
和div
元素,并从匹配集中删除那些不满足所需字数的元素。
我已经测试了wordCount
插件和它正在使用的if
语句,一切似乎都很好,但我的元素并没有从匹配的集合中删除。
(function($){
$.fn.extend({
textBlocks: function(count){
var JQ_Object = $(this);
if(!count) count = 100;
return this.each(function(){
$(this).find("p, div").each(function(){
if($(this).wordCount()<count){
var x = $(this);
JQ_Object.not(x);
};
});
return JQ_Object;
});
}
});
})(jQuery);
这是wordCount插件,以防你想知道:
(function($){
$.fn.extend({
wordCount: function(){
return $(this).html().split(" ").length;
}
});
})(jQuery);
我做了一些更改。。。请参阅fiddle的工作示例和代码的注释。
http://jsfiddle.net/8PXpt/
(function ($){
$.fn.extend({
wordCount: function (){
//Don't need $(this), this already refers to the jQuery object
//Always trim .html() and .text() when using .split()
//May want to use .text() instead of .html() - I leave that to you
return $.trim(this.html()).split(' ').length;
}
});
})(jQuery);
(function ($){
$.fn.extend({
textBlocks: function (count){
var collection = this;
//Check that a number was passed
//"50" would break your extension
if(typeof count !== 'number') {
count = 100;
}
//Removed $('div, p') - this should be part of your call
//See ready function below
this.each(function (){
if ($(this).wordCount() < count){
//This could be double assignment
//but better safe than sorry
collection = collection.not(this);
};
});
//Return what is left (what passed)
return collection ;
}
});
})(jQuery);
$(function() {
//Here is where you define your selector... in your case 'div, p'
$('div, p').textBlocks(2);
});
您尝试过$(this).remove()
而不是JQ_Object.not(x);
吗
我认为.not()
将它们从选择中删除,而不是从HTML中删除。。。除非这是你想要做的
您正在内部each中创建一个新的JQ_Object,所以我不确定它是否会修改原始的JQ_Object。不过,我并不是百分之百相信这一点。尝试JQ_Object.而不是(这个).
然而,这是假设每个都是同步的,我希望不是。如果是这种情况,您需要使用jQuery的while函数。
这应该会给你想要的结果,但我会注意每一个都是异步的。
return $(this).find("p, div").each(function(){
if($(this).wordCount()<count){
JQ_Object.not(this);
};
});
编辑:
我不确定上面的代码。我要做的是使用回调。这假设回调被传递到插件中。
$(this).find("p, div").each(function(){
if($(this).wordCount()<count){
JQ_Object.not(this);
};
}).when(function () {
callback(JQ_Object);
});
相关文章:
- 如何查找流星集合中最后一个元素/对象的id
- 如何在JSXGraph中传递元素对象而不是id
- 手动呈现原型JS元素对象
- 为什么jQuery's每个循环的函数都保存对元素对象的引用
- 通过 html 图像元素对象显示图像
- 在 Plain/Pure Javascript 中,你如何找出元素对象具有哪些可用的方法或属性
- 如何在Angualar的jqLite元素对象中按id查找元素
- XPath 元素/对象在使用 document.evaluate 时未定义
- 如何使用JQuery获取元素对象
- 使用jQuery元素对象作为数组键
- 传递元素对象
- Mootools元素>对象# & lt; HTMLDivElement>没有方法'addEvent'
- 迭代所有节点对象,而不仅仅是元素对象
- 当一个元素被点击时,另一个元素(对象)发送给函数
- 正在分配属性'由getElementById()在语句中返回的HTML元素对象的s
- 创建一个新的用户界面元素对象的Javascript原型
- 在javascript中继承了DOM元素对象!这段代码有什么问题?
- AppendChild不工作!,从DOM元素对象继承.我做错了什么?
- 有没有办法“得到”?就像getElementById()能够获取html元素对象一样,使用函数来获取javascript
- 如何返回javascript DOM元素对象,并从调用者appendChild(obj)它