2013-04-22 62 views
0

我遇到一個問題,從select中獲取值並將其放在var上。從select中獲取一個變量值並將其傳遞給另一個JS文件

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; 

任何幫助表示讚賞!

+0

'customer_select'是本地的'findcustid',當你執行'VAR和客戶id = customer_select不存在;'。你聲稱擁有的問題究竟是什麼? – 2013-04-22 15:39:13

回答

2

您的customer_select變量是本地功能的範圍將不可用的功能。

var customer_id; 
function findcustid() { 
    var cus = document.getElementById('customer_select'); 
    customer_id = document.getElementById('customer_select').value; 
} 

的另一種方式,你可以,如果不是使用全局cutomer_id變量做,這是在當前window實例 前將其設置: -

function findcustid() { 
    var cus = document.getElementById('customer_select'); 
    window.customer_id = document.getElementById('customer_select').value; 
} 

現在你可以在定義的任何函數訪問window.customer_id當前窗口的範圍。

0

您選擇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); 
} 

之前,您不能設置因爲函數還沒有被調用,但代碼被執行,所以最後用你的代碼,customer_id將是undefined

0

首先Niels是正確的,你關閉你的函數,然後再對變量做任何事情。 兩種可能的解決方案。

此外,我對你的意思是「傳遞給另一個JS文件」有點困惑......你不能將它傳遞給另一個頁面,而無需將其作爲URL或表單變量並轉到該頁面。

或..如果JS包括在同一頁上,剛剛從任何其他包含的功能調用前聲明此功能:

<script src="../customerFuncs.js"></script> 
<script src="../useCustomerFuncs.js"></script> 
  1. 如果你需要CUSTOMER_ID別的地方,將其設置爲該函數的返回值和調用該函數從另一個函數,鼻翼:

    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(); 
    } 
    
  2. 你可以把它的任何功能的全局變量訪問。你可以通過在任何函數範圍外聲明它來做到這一點。這種方法真的不好受,因爲它通常不是必需的。

    gCustomer_Id = ''; 
    
    function findcustid(){ 
        ... 
        gCustomer_Id = customer_select; 
    } 
    
相關問題