从函数返回更新变量
Return updating variable from function
我正在尝试使用 javascript/jQuery 来查找窗口的宽度并在后面的函数中使用该变量。
$(function resizer() {
function doneResizing() {
var windowWidth = $(window).width();
return windowWidth;
}
var getWidth = doneResizing();
var id;
$(window).resize(function() {
clearTimeout(id);
id = setTimeout(doneResizing, 0);
});
doneResizing();
return getWidth;
});
var finalWidth = resizer()
因此,每当调整窗口大小并自动更新windowWidth
时,调整大小函数就会更新。当变量在函数外部返回时,除非我刷新页面,否则getWidth
不会通过窗口大小调整进行更新。有什么想法吗?我 2 周前刚刚拿起 js/jq,我正在尽最大努力解决退货和关闭问题,所以我可能忽略了这里的一些东西。谢谢。
执行以下操作
要简单得多:
var finalWidth;
$( document ).ready(function() {
//Set this the first time
finalWidth = $(window).width();
$(window).resize(function() {
//resize just happened, pixels changed
finalWidth = $(window).width();
alert(finalWidth); //and whatever else you want to do
anotherFunction(finalWidth);
});
});
并在外部使用最终宽度,因为它是全局变量。您可以获得相同的功能,而不会变得复杂。
更新
正如评论的那样,全局变量是不好的实践(例如,也是 http://dev.opera.com/articles/view/javascript-best-practices/)。
为了避免全局变量finalWidth
可以在document.ready
内部移动,并且可以从事件处理程序内部调用任何必要的函数resize(function() {
。
更新 2
由于拖动导致多个调整大小事件的问题,代码已更新。
参考:JQuery:如何在完成调整大小后调用调整大小事件?
JSFiddle: http://jsfiddle.net/8ATyz/1/
$( document ).ready(function() {
var resizeTimeout;
$(window).resize(function() {
clearTimeout(resizeTimeout);
resizeTimeout= setTimeout(doneResizing, 500);
});
doneResizing(); //trigger resize handling code for initialization
});
function doneResizing()
{
//resize just happened, pixels changed
finalWidth = $(window).width();
alert(finalWidth); //and whatever else you want to do
anotherFunction(finalWidth);
}
function anotherFunction(finalWidth)
{
alert("This is anotherFunction:"+finalWidth);
}
你把resizer
函数和jQuery ready
函数混为一谈了。要跟踪窗口宽度,您可以这样做
(function ($) {
var windowWidth;
// when the document is fully loaded
$(function(){
// add an resize-event listener to the window
$(window).resize(function(){
// that updates the variable windowWidth
windowWidth = $(window).width();
})
// trigger a resize to initialize windowWidth
.trigger('resize');
// use windowWidth here.
// will be updated on window resize.
});
}(jQuery));
相关文章:
- React:使用索引变量更新嵌套集合
- 范围变量更新,但不更新视图
- 正在将代码库中的C#变量更新到asp.net
- 使用变量更新剑道图表系列的数据会导致重绘将列从图表上绘制出来
- MongoDB 用变量更新数组
- 将变量更新为函数中的参数
- Javascript-变量更新
- 使用Javascript和PHP变量更新页面上的数据
- Angular js 在
标签上的变量更新$scope动画
- 如何通过参数变量更新对象的属性值
- 如何在范围变量更新时更新模板
- 简单的变量更新和写入页
- 函数在变量更新后的某个时间点执行
- javascript OO如何用一些JSON变量更新self参数
- 使用$set中的变量更新mongodb的node.js
- 将声明的null变量更新为布尔值
- 在查询部分使用变量更新查询
- 如何在回调中使用变量更新文档?
- 通过AJAX用PHP变量更新URL
- 防止在没有javascript的情况下在页面刷新后进行变量更新