gpt4 book ai didi

Jquery UI 小部件工厂

转载 作者:行者123 更新时间:2023-12-01 03:39:30 25 4
gpt4 key购买 nike

$.widget( "app.serverTime", {
_create: function () {
$.get("/timestamp.php", function( data ) {
this.timestamp = data.timestamp;
})
},

getTime:function() {
return this.timestamp;
}
});


$(".clock").serverTime();
$(".clock").serverTime("getTime")

我有上面的 jQuery UI 小部件,当我调用 getTime 时,我得到了预期的值,但相反,我得到了 jQuery 选择器,当我手动设置值而不使用 Ajax 时,它按预期工作。

最佳答案

我认为问题是因为这个。在 get 函数内部,this 不引用插件 calee 对象。

因此请保存引用并稍后使用它,例如:

$.widget( "app.serverTime", {
_create: function () {
var _this=this;
$.get("/timestamp.php", function( data ) {
_this.timestamp = data.timestamp;
})
},

getTime:function() {
return this.timestamp;
}
});

编辑

考虑到 $.get 是异步的,因此时间戳属性将在 $.get 完成但代码运行时设置。

概念:

$(".clock").serverTime();

setTimeout(function () {
console.log($(".clock").serverTime("getTime"));
}, 5000);

因此请考虑正确处理异步。

演示:http://jsfiddle.net/IrvinDominin/5pFkk/

关于Jquery UI 小部件工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24752136/

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