gpt4 book ai didi

javascript - 在事件期间将值保存到全局变量中以供以后使用

转载 作者:行者123 更新时间:2023-12-02 22:02:28 28 4
gpt4 key购买 nike

我想知道如何实现以下功能。

我有一个全局变量,当文本框获得焦点时,它会被分配一个值。我希望能够在事件之外访问这个新值以供以后使用,但显然通过以下实现,该值变得未定义。有办法克服这个问题吗?

var globalVar;

$('.inputIdentifier').on('focus', function() {
globalVar = $(this).attr('data-val');
console.log(globalVar);
});

//access the value in globalVar outside the function?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="inputIdentifier" data-val="myData" />

谢谢。

最佳答案

仅当 .inputIdentifier 获得焦点时,它的值才会分配给 globalVarfocus 下面的代码在用户聚焦于输入之前运行,因此您的 globalVar 仍然是未定义的。您将从我在下面添加的 console.log 中看到这一点。您可以在 focus 中调用另一个函数并将 globalVar 作为参数传递吗?

var globalVar;

$('.inputIdentifier').on('focus', function() {
globalVar = $(this).attr('data-val');
console.log('globalVar on focus', globalVar);
doSomething(globalVar);
});

//You will not get the value of $(this).attr('data-val') here. globalVar only gets set when the onFocus of .inputIdentifier
console.log('globalVar on initial run', globalVar);

function doSomething(globalVar){
console.log('globalVar in doSomething', globalVar);
}

关于javascript - 在事件期间将值保存到全局变量中以供以后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59831863/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com