[英]get a variable value from select and pass this to another JS file
我在从select中获取价值并将其放在var中时遇到问题。
HTML
<select id="customer_select"" name="customer_select" class="select" onchange="findcustid(this.value)" >';
JS
function findcustid() {
var cus = document.getElementById('customer_select');
var customer_select = cus.options[cus.selectedIndex].value;
}
var customer_id = customer_select;
任何帮助表示赞赏!
您的customer_select变量在功能范围内是本地的,在该功能之外将不可用。
var customer_id;
function findcustid() {
var cus = document.getElementById('customer_select');
customer_id = document.getElementById('customer_select').value;
}
如果不使用全局cutomer_id变量,则可以执行此操作的另一种方法是在当前window
实例ex中进行设置:
function findcustid() {
var cus = document.getElementById('customer_select');
window.customer_id = document.getElementById('customer_select').value;
}
现在,您可以在当前窗口范围内定义的任何函数中访问window.customer_id
。
您选择“ HTML有很多”,首先更改为:
<select id="customer_select" name="customer_select" class="select" onchange="findcustid(this.value)" >
另外,您在设置customer_id之前关闭了该功能,将其更改为
function findcustid() {
var cus = document.getElementById('customer_select');
var customer_select = cus.options[cus.selectedIndex].value;
var customer_id = customer_select;
alert(customer_id);
}
关闭功能后,您将无法设置项目。 因为该函数尚未调用,但代码已执行。 所以最后,您的代码将undefined
customer_id
首先,尼尔斯(Niels)是正确的,您在对变量执行任何操作之前已关闭函数。 两种可能的解决方案。
另外,我对您的意思是“传递到另一个JS文件”感到有些困惑……如果不将其设为url或form变量并转到该页面,就无法将其传递给另一个页面。
或..如果js包含在同一页面上,只需在从任何其他包含的函数调用它之前声明此函数:
<script src="../customerFuncs.js"></script>
<script src="../useCustomerFuncs.js"></script>
如果您在其他地方需要customer_id,请将其设置为该函数的返回值,然后从另一个函数ala调用该函数:
function findcustid(){ var cus = document.getElementById('customer_select'); var customer_select = cus.options[cus.selectedIndex].value; var customer_id = customer_select; return customer_id; } function getId(){ customer_id = findcustid(); }
您可以将其设为任何函数都可以访问的全局变量。 您可以通过在任何函数范围之外声明它来实现。 这种方法的确很皱眉,因为通常不需要。
gCustomer_Id = ''; function findcustid(){ ... gCustomer_Id = customer_select; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.