如何跨函数/变量访问javascript值?

那么,三个小部分:

1)MaxMind地理IP查找,通过IP地址获取国家/地区代码:

var onSuccess = function(x){ var ip = x.traits.ip_address; document.getElementById('ip_address').value = ip; var country_code = x.country.iso_code; document.getElementById('ip_country_code').value = country_code; … }; 

2)包含税率百分比的国家/地区参考数组:

 // Array of values for tax rates var tax_rates= new Array(); tax_rates["noteu"]=0.0; tax_rates["ES"]=21.0; tax_rates["AU"]=20.5; tax_rates["BE"]=21.7; … 

3)TaxPrice函数,它使用其中一个小数来计算税额,然后在订阅表单中计算应付总额。 请注意XXXXX:

 function TaxPrice() { var taxprice=0; XXXXX return taxprice; } 

1)中的document.getElementById位显然可以更新隐藏字段或其他一些HTML元素。

我知道如果用户必须选择手动下拉菜单,该如何处理XXXXX。

但是如何根据IP地址国家代码从数组和TaxPrice函数中获取税号? (即在javascript中,不更新HTML元素)。

祝大家新年快乐。

更新:为了清楚,我不需要知道如何将它变成一个下拉列表,我已经可以做到这一点,在这个用例中,用户不应该被允许选择他自己的税收国家,它应该是根据IP地址自动设置。 因此,非代码措辞将类似于:

taxprice EQUALS tax_rate.value ACCORDING TO ip_address_code

你在寻找像元素属性这样的东西吗? Mydiv.tax = taxvalue; Elements的属性是在不同function之间进行通信的优雅方式。 您可以为任何元素分配任何值。 只要Basic元素存在,您就可以从JavaScript中的任何函数中检索值。

你可以做的一种方法是在你的成功回调中设置一个全局的selectedCountryCode变量,并在你的TaxPrice数组中引用tax_rates[selectedCountryCode] (它应该是一个对象,如nnnnnn指出的那样)

 (function () { var selectedCountryCode = ""; var onSuccess = function(x) { var ip = x.traits.ip_address; document.getElementById('ip_address').value = ip; selectedCountryCode = x.country.iso_code; // <-- Set selectedCountryCode for later use document.getElementById('ip_country_code').value = selectedCountryCode; // <-- Set dropdown value }; document.getElementById("ip_country_code").addEventListener("change", function() { selectedCountryCode = this.value; console.log(TaxPrice()); }); // Object of values for tax rates var tax_rates = {}; tax_rates["noteu"] = 0.0; tax_rates["ES"] = 21.0; tax_rates["AU"] = 20.5; tax_rates["BE"] = 21.7; function TaxPrice() { var taxprice = 0; taxprice = tax_rates[selectedCountryCode]; return taxprice; } })(); 
 Change Me:  

所以,谢谢你的建议。 不知道我是否理解这是如何工作的,但经过一些探讨,现在就是。 与原始问题中的代码相比,我不得不:

1)在顶部添加一个全局变量,高于其他所有内容,与IP查找代码无关(即,现在IP onSuccess变量中没有对country_tax引用):

 var country_tax; 

2)将TaxPricefunction中的XXXXX替换为:

 var country_tax = document.getElementById("ip_country_code").value; var taxprice = taxes_from_database[country_tax]; 

因此,完整的TaxPrice函数最终为:

 function TaxPrice() { var taxprice = 0; var country_tax = document.getElementById("ip_country_code").value; var taxprice = tax_rates[country_tax]; return taxprice; } 

似乎不需要嵌套函数或闭包或任何非常复杂的东西。 对于代码来说,如果将tax_rates设置为数组或对象并不重要,结果是相同的,尽管我想理解为什么在这种情况下为数组推荐一个对象。

并且给定的TaxPrice从表单字段获取值而不是从IP onSuccess函数中获取 – 我不知道为什么我需要顶部的全局变量声明,如果有人想要解释那个…