2016-03-10 99 views
0

分配文本框的值時,我有以下文本框:問題瓦爾

<input type="textbox" name="number-of-standard-investors" class="enquiry" id="nostandinv" /> 

我試圖在此文本框的值賦給一個變種,像這樣:

$(document).ready(function(){ 

    var number_of_standing_investments = $('#nostandinv').val(text); 

    $("#nostandinv").keyup(function(){ 
     //console.log(number_of_standing_investments); 

     alert(number_of_standing_investments); 
    }); 
}); 

然而number_of_standing_investments永遠不會分配價值,任何人都可以提出問題在這裏?

感謝

回答

1

下面的代碼是一個二傳手,也是text不是在這個時候定義的,它拋出一個ReferenceError

var number_of_standing_investments = $('#nostandinv').val(text); 

您需要使用吸氣

var number_of_standing_investments = $('#nostandinv').val(); 

看起來您需要在提醒時動態分配它。所以這樣做:

$("#nostandinv").keyup(function(){ 
    //console.log(number_of_standing_investments); 
    number_of_standing_investments = this.value; 
    alert(number_of_standing_investments); 
}); 

number_of_standing_investments範圍已經在全球範圍,到$(document)ready函數中的任何訪問。

+1

From:Performance perspective'number_of_standingvestments = this.value;'會更好 – Satpal

+0

@Satpal已更新。 ':)' –

1

使用number_of_standing_investments = $('#nostandinv').val();裏面的密碼功能。

我發現一個錯誤是$('#nostandinv').val(text)它會顯示錯誤,因爲變量文本沒有定義。

$(document).ready(function(){ 
 

 
    var number_of_standing_investments = $('#nostandinv').val(); 
 

 
    $("#nostandinv").keyup(function(){ 
 
     number_of_standing_investments = $('#nostandinv').val(); 
 
     alert(number_of_standing_investments); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="textbox" name="number-of-standard-investors" class="enquiry" id="nostandinv" />
內KEYUP文本框的

+0

謝謝,是否有可能讓number_of_standing_investments可以在全球範圍內使用? –

+1

@Liam它已經在全球範圍內。 –

+0

@Liam只要你沒有在一個不同的函數中聲明一個具有相同名字的變量,它的作用域就不會改變。根據你的代碼,它已經是全球範圍。 –

1

獲得價值。您正在將文本框值保存在就緒狀態。所以它會一直存儲你的文本框的初始值。

$(document).ready(function(){ 
    $("#nostandinv").keyup(function(){ 
     //console.log(number_of_standing_investments); 
     var number_of_standing_investments = $(this).val(); 
     alert(number_of_standing_investments); 
    }); 
});