【问题标题】:cannot get a variable from a prompt as a callback function无法从提示中获取变量作为回调函数
【发布时间】:2020-01-22 18:18:18
【问题描述】:
在button上右击我需要:
- 隐藏按钮
- 然后显示提示
- 写入提示值
- 获取控制台中的值
function a_ren(){
var a = 'lorem';
$('.cmenu').hide(function(){var res = prompt('RENAME', a);});
console.log(res);
}
$(document).on('contextmenu', 'button', function(e){
e.preventDefault();
a_ren();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='cmenu'>CLICK</button>
两个问题:
- 控制台错误 - res 未定义
- 在SO 上出现提示窗口,但在我的页面(chrome,localhost)上根本没有出现提示窗口。
有什么帮助吗?
【问题讨论】:
标签:
javascript
jquery
prompt
【解决方案1】:
未定义res 的原因是因为传递给hide() 的函数直到隐藏动画完成后才会运行,但console.log(res); 无需等待即可调用。此外,正如 Ram Segev 所指出的,res 是在 hide 回调函数中定义的,因此这是它在范围内的唯一位置(可访问)。
至于没有出现提示,换个试试
$(document).on('contextmenu', 'button', function(e){
到
document.querySelector('button').addEventListener('contextmenu', (e) => {
【解决方案2】:
res 未定义,因为您在 hide 函数内声明它并尝试在它之外打印它(不在范围内)。将控制台日志放在函数中,它应该可以解决它。
function a_ren(){
var a = 'lorem';
$('.cmenu').hide(function(){
var res = prompt('RENAME', a);
console.log(res);
});
}
$(document).on('contextmenu', 'button', function(e){
e.preventDefault();
a_ren();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='cmenu'>CLICK</button>
【解决方案3】:
问题是var res的作用域在隐藏完成回调内,即使你在函数外声明res你也不会从提示中获取值,因为隐藏完成回调是异步的,所以你必须处理回调内部的提示结果,参考以下代码
function a_ren() {
var a = 'lorem';
$('.cmenu').hide(function () {
var res = prompt('RENAME', a);
process_prompt_result(res);
// scope of res ends here, its undefined outside this function
});
}
$(document).on('contextmenu', 'button', function (e) {
e.preventDefault();
a_ren();
});
function process_prompt_result(result) {
// do something thing with result value from prompt
console.log(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='cmenu'>CLICK</button>