将Javascript局部变量转换为全局变量

时间:2020-12-14 16:49:54

I tried a solution presented in several other topics here, but for some reason, it doesn't work for me

我在这里尝试了其他几个主题的解决方案,但由于某些原因,它对我不起作用

$(function() {
$('.talk').live('click', 'button', function()
{
var user1 = $(this).val();
var user2=$(this).prev().val();
window.user=user1;
window.recipient=user2;

})
})

(...)

console.log(window.user);
var refresh = setInterval(function(){ myTimer() }, 1000);
function myTimer() {loadchat(window.user,window.recipient);
}
function myStopFunction() {clearInterval(refresh);}

I need the function loadchat to receive the parameters user1 and user2, but they are confined withing the first function i pasted here. I read that if i use window.user1= it will work, but it won't.

我需要函数loadchat来接收参数user1和user2,但是它们被限制在我粘贴的第一个函数中。我读过如果我使用window.user1 =它会起作用,但它不会。

The way it is right now, the console.log(window.user) will return "undefined" (i also tried just "user" instead of window.user)

它现在的方式,console.log(window.user)将返回“undefined”(我也尝试了“user”而不是window.user)

2 个解决方案

#1


0  

Define your global value outside the function

在函数外定义全局值

<script>
var globalVariable;
function()
{
   globalVariable = $(this).val();
}
</script>

#2


0  

what I can understood of your question is this you need a way to store user and recipient

我能理解你的问题是你需要一种存储用户和收件人的方法

You can use this

你可以用它

$(function() {
$('.talk').live('click', 'button', function() {
   var user1 = $(this).val();
   var user2=$(this).prev().val();

   localStorage.setItem("User", user1);
   localStorage.setItem("recipient", user2);
  })
})

can retrieve your data with the function localStorage.getItem("User");

可以使用函数localStorage.getItem(“User”)检索您的数据;

but this is problematic because the data will stay remain in memory after close the tab to solve this you need to use sessions vars

但这是有问题的,因为关闭选项卡后数据将保留在内存中以解决此问题,您需要使用会话变量

sessionStorage.setItem("User", user1);
sessionStorage.getItem("User");

#1


0  

Define your global value outside the function

在函数外定义全局值

<script>
var globalVariable;
function()
{
   globalVariable = $(this).val();
}
</script>

#2


0  

what I can understood of your question is this you need a way to store user and recipient

我能理解你的问题是你需要一种存储用户和收件人的方法

You can use this

你可以用它

$(function() {
$('.talk').live('click', 'button', function() {
   var user1 = $(this).val();
   var user2=$(this).prev().val();

   localStorage.setItem("User", user1);
   localStorage.setItem("recipient", user2);
  })
})

can retrieve your data with the function localStorage.getItem("User");

可以使用函数localStorage.getItem(“User”)检索您的数据;

but this is problematic because the data will stay remain in memory after close the tab to solve this you need to use sessions vars

但这是有问题的,因为关闭选项卡后数据将保留在内存中以解决此问题,您需要使用会话变量

sessionStorage.setItem("User", user1);
sessionStorage.getItem("User");