Mat*_*iby 1 javascript jquery scope
我有这个功能
function update_prices(product_selector){
//kind of a hack to account for the sometimes having a professional price and sometimes not
var price_count = product_selector.find('small.rt').length;
for (i=0;i<=price_count;i++)
{
if(i == 0){
var standard_selector = product_selector.find('small.rt:eq('+ i +')');
var standard_price = standard_selector.attr('data');
}
if(i == 1){
var business_selector = product_selector.find('small.rt:eq('+ i +')');
var business_price = business_selector.attr('data');
}
if(i == 2){
var professional_selector = product_selector.find('small.rt:eq('+ i +')');
var professional_price = professional_selector.attr('data');
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有这个称之为的代码块
....
....
product_selector.find(".active_selector").removeClass('active_selector');
update_prices(product_selector);
....
....
standard_selector.text("something");
business_selector.text("something else");
professional_selector.text("another thing");
Run Code Online (Sandbox Code Playgroud)
我的问题是我如何保留三个变量的范围,standard_selector business_selector并professional_selector在update_prices函数中创建
要在函数声明后保持这些变量持久化,您有以下选择:
最简单的解决方案(并不总是最好的)是通过在更高的范围内声明它们var并在函数中移除它们前面来使它们成为全局变量,这样您只需操作全局变量而不是使用局部变量:
// declare global variables in global scope
var standard_selector;
var business_selector;
var profession_selector;
function update_prices(product_selector){
//kind of a hack to account for the sometimes having a professional price and sometimes not
var price_count = product_selector.find('small.rt').length;
for (i=0;i<=price_count;i++)
{
if(i == 0){
standard_selector = product_selector.find('small.rt:eq('+ i +')');
var standard_price = standard_selector.attr('data');
}
if(i == 1){
business_selector = product_selector.find('small.rt:eq('+ i +')');
var business_price = business_selector.attr('data');
}
if(i == 2){
professional_selector = product_selector.find('small.rt:eq('+ i +')');
var professional_price = professional_selector.attr('data');
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想从此函数返回它们,以便可以在范围内使用它们,则可以在对象中返回它们:
function update_prices(product_selector){
//kind of a hack to account for the sometimes having a professional price and sometimes not
var sel = {};
var price_count = product_selector.find('small.rt').length;
for (i=0;i<=price_count;i++)
{
if(i == 0){
sel.standard_selector = product_selector.find('small.rt:eq('+ i +')');
var standard_price = standard_selector.attr('data');
}
if(i == 1){
sel.business_selector = product_selector.find('small.rt:eq('+ i +')');
var business_price = business_selector.attr('data');
}
if(i == 2){
sel.professional_selector = product_selector.find('small.rt:eq('+ i +')');
var professional_price = professional_selector.attr('data');
}
}
return(sel);
}
var selectors = update_prices(xxx);
// access selectors.standard_selector, selectors.business_selector, selectors.profession_selector here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
200 次 |
| 最近记录: |