从插件中删除jQuery对象中的元素

remove elements from the jQuery object from within a plugin

本文关键字:元素 对象 删除 插件 jQuery      更新时间:2023-09-26

我认为我在这里弄错了一些基本原理,因为我认为这应该有效。我正在尝试通过匹配集的子pdiv元素,并从匹配集中删除那些不满足所需字数的元素。

我已经测试了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);
});