How can I refresh a stored and snapshotted jquery selector variable

后端 未结 6 1581
温柔的废话
温柔的废话 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:57

    I also liked @Esailija solution, but seems that this.selector has some bugs with filter. So I modified to my needs, maybe it will be useful to someone

    This was for jQuery 1.7.2 didn`t test refresh on filtered snapshots on higher versions

    $.fn.refresh = function() { // refresh seletor
        var m = this.selector.match(/\.filter\([.\S+\d?(\,\s2)]*\)/); // catch filter string
        var elems = null;
        if (m != null) { // if no filter, then do the evarage workflow
            var filter = m[0].match(/\([.\S+\d?(\,\s2)]*\)/)[0].replace(/[\(\)']+/g,'');
            this.selector = this.selector.replace(m[0],''); // remove filter from selector
            elems = $(this.selector).filter(filter); // enable filter for it
        } else {
            elems = $(this.selector);
        }
        this.splice(0, this.length);
        this.push.apply( this, elems );
        return this;
    };
    

    Code is not so beautiful, but it worked for my filtered selectors.

提交回复
热议问题