How can I refresh a stored and snapshotted jquery selector variable

后端 未结 6 1578
温柔的废话
温柔的废话 2020-12-13 13:46

I ran yesterday in a problem with a jquery-selector I assigned to a variable and it\'s driving me mad.

Here is a jsfiddle with testcase:

  • assign the .el
6条回答
  •  北海茫月
    2020-12-13 13:54

    Clean and generic solution worked properly with jQuery 3.4.1:

    My solution is to do the following:

    1. Intercept the selector at the time of jQuery object initialization and in the same time maintain all other jQuery functionalities transparently all this using inheritance
    2. Build refresh plugin that make use of the new "selector" property we added during initialization

    Definition:

    $ = (function (originalJQuery) 
    {
        return (function () 
        {
            var newJQuery = originalJQuery.apply(this, arguments);
            newJQuery.selector = arguments.length > 0 ? arguments[0] : null;
            return newJQuery;
        });
    })($);
    
    $.fn = $.prototype = jQuery.fn;
    
    $.fn.refresh = function () 
    {
        if (this.selector != null && (typeof this.selector === 'string' || this.selector instanceof String))
        {
            var elems = $(this.selector);
            this.splice(0, this.length);
            this.push.apply(this, elems);
        }
        return this;
    };
    

    Usage:

    var myAnchors = $('p > a');
    //Manipulate your DOM and make changes to be captured by the refresh plugin....
    myAnchors.refresh();
    //Now, myAnchors variable will hold a fresh snapshot 
    

    Note: As optimization, object selectors don't need refresh as they are pass by reference by nature so, in refresh plugin, we only refresh if the selector is a string selector not object selector for clarification, consider the following code:

    // Define a plain object
    var foo = { foo: "bar", hello: "world" };
     
    // Pass it to the jQuery function
    var $foo = $( foo );
     
    // Test accessing property values
    var test1 = $foo.prop( "foo" ); // bar
    
    // Change the original object
    foo.foo = "koko";
    
    // Test updated property value
    var test2 = $foo.prop( "foo" ); // koko
    

提交回复
热议问题