如何从jquery函数返回变量

How to return variable from jquery function

本文关键字:返回 变量 函数 jquery      更新时间:2023-09-26

你能帮我吗。。。如何从jquery函数返回变量

var height = $(window).height();
$(window).resize(function(){
    var height = $(window).height();
    return height;
});
setInterval(function() {
    $('div').append( 'Index: ' +  height );
}, 500);

您不需要返回。试试这个:

var height = $(window).height(); // define "height" here
$(window).resize(function(){
    height = $(window).height(); // update "height" variable, 
                                 // don't user "var" here.
                                 // because using "var" will redefine
                                 // "height" again and no longer contain the
                                 // updated value on window resize 
                                 // out of this resize function scope
});
setInterval(function() {
    $('div').append( 'Index: ' +  height );
}, 500);

当您使用var时,您正在创建一个新变量,而不是覆盖原始变量。你会想要这个:

var height = $(window).height();
$(window).resize(function() {
    height = $(window).height();
});
// ...

我想你的问题的答案取决于你想如何返回它。控制台?警觉的div还是其他元素?请参阅下面的列表。

  • console.log(高度)
  • 警报(高度)
  • $("#elementID").html(高度);//或者适用于您的案例的任何选择器和方法

我想你也可以把$(window).resize块转换成一个函数,然后调用那个函数。这也应该奏效。