我有一段代码,我希望每10秒左右执行一次,同时还要按一下按钮单击事件。我应该创建一个函数来节省编码重复吗?我会在页面上有很多按钮来触发这段代码,但是我意识到我可以使用类选择器来触发代码。我需要定时器间隔,因为第三方将能够更改代码正在检查的值,我不关心定时器是否超级准确。jquery创建自己的函数?
如何将代码更改为函数?我已经看到了一些创建函数的例子,但我没有看到符合我的要求的任何东西。
//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);
}
});
});
});
感谢您的任何想法和帮助
_“我应该创建一个函数来节省编码重复吗?”_ - 是的。 – nnnnnn
您可以使用函数funName(argList,...){code here}'定义一个函数,任何在您的函数中应该变量的东西都应该作为参数传递给它。详细了解功能:http://eloquentjavascript.net/chapter3.html。 –
你确定显示的代码有效吗?我注意到在使用'$('img')。attr('src','lightbulbon.png')'的Ajax成功处理程序中,它将页面上每个img元素的src设置为相同的东西。 – nnnnnn