Calculating Variables from Variables from ids

2019-09-11 15:29发布

问题:

The following code placed in document.ready() finds every .scrollable div and creates a variable giving each panel an id and activating a scrolling script.

var orderit = 0;
var scrolls = {};
$('.scrollable').each(function(){
    this.id = 'scrollp' + (++orderit);
    scrolls[ 'myScroll' + this.id ] = new iScroll( this.id, { scrollbarClass: 'myScrollbar' });
});

The problem is that later on I need to refresh these variables by calling the .refresh() method embedded in the script. To do this we need the variable name. One way to get the variable would be to calculate its setup like this.

$('.dircore').click(function(){
    'myScroll' + $(this).attr('id').refresh();
}

This works in firefox only even though firebug says it is an error, but it does not work in other browsers and is clearly not the correct way of doing this.

I hope there is enough information to work off here but essentially we need to use the id of the element we want to refresh to work out it's variable and consequently call the .refresh() method against its variable.

回答1:

Can't you use the jQuery .data() function to bind the data to the element, and recall it later? This way you're also safe from circular references and memory leaks caused by them.

Like this:

$(document).ready(function() { $('#scroll5').data('data', value ); });

And then:

$('.dircore').each(function() { $(this).data('data').refresh(); });

Or something like that.