Calculating Variables from Variables from ids

妖精的绣舞 提交于 2019-12-12 01:14:53

问题


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.



来源:https://stackoverflow.com/questions/7806322/calculating-variables-from-variables-from-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!