[英]Global variables not changing through function
我試圖獲取一個人當前在鍵盤輸入中使用的輸入框的值和名稱,但是一旦鍵盤輸入功能運行后,全局變量就無法更新。 他們只是繼續說在Google Chrome開發人員工具中未定義。
我究竟做錯了什么?
$( document ).ready(function() {
var assessName;
var assessVal;
var impName;
var impVal;
//Get the name and value of the currently selected assessed input
$('[id^=ass]').on('keyup', function(){
assessName = $(this).attr('name').replace('ass-','');
assessVal = $(this).val();
});
//Get the name and value of the currently selected implemented input
$('[id^=imp]').on('keyup', function(){
impName = $(this).attr('name').replace('imp-','');
impVal = $(this).val();
});
console.log(assessName);
console.log(assessVal);
console.log(impName);
console.log(impVal);
});
發生這種情況是因為keyup
事件在將variables
寫入控制台后會更改variables
。 JavaScript中的事件是異步的 。
因此,如果將console.log
調用放入事件偵聽器中,它將完全顯示您的期望。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.