我有一个代码块,我想每 10 秒左右执行一次,也可以在按钮单击事件上执行。我应该创建一个函数来节省编码重复吗?我将在页面上有很多按钮来触发这段代码,但我意识到我可以使用类选择器来触发代码。我需要计时器间隔,因为第 3 方将能够更改代码正在检查的值,我不关心计时器是否超级准确。
如何将代码更改为函数?我已经看到了一些创建函数的示例,但没有看到任何符合我要求的示例。
//This Ajax checks the current on/off status of the passed X10 code
$('img.checkStatus').each(function(i, obj) {
$x10Device = $(this).data("x10");
var data="url=http://192.168.0.34:81/tenHsServer/tenHsServer.aspx? t=ab&f=DeviceStatus&d=" + $x10Device ;
$.ajax({
url:"urlencode.php",
data: data,
type: "POST",
success: function(data) {
myd = $('<span />').html(data).find("#Result").text();
var Nmyd = myd.charAt(3);
if (Nmyd == '2'){
$('img').attr('src','lightbulbon.png')
}
else{
$('img').attr('src','lightbulboff.png')};
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
});
感谢您的任何想法和帮助