好吧,我正在尝试通过更改元素的 id 并将两个不同的函数应用于不同的 id 来启动/停止 setInterval 函数。这是目前的代码:
$(document).ready(function(){
var seq
$('#start').click(function(){
$(this).attr('id','stop');
seq=self.setInterval(function(){blah()},125);
});
$('#stop').click(function(){
$(this).attr('id','start');
clearInterval(seq);
});
});
当我单击 #start 元素时,setInterval 启动并且 id 更改为 #stop,但是如果我再次单击(在现在称为 #stop 的元素上),则会执行 #start 的代码(添加另一个 setInterval) ) 谢谢
函数“blah”只是一个虚构函数的示例
最佳答案
当你说:
$('some selector').click(...
它将点击处理程序绑定(bind)到与某个选择器
匹配的所有元素当时 - 它不会自动应用于将来可能匹配的元素。
要让处理程序应用于在单击事件时与选择器匹配的元素,您需要使用委托(delegate)事件处理程序,这意味着将处理程序附加到父元素(或 document
如果该元素没有静态父元素):
$(document).ready(function(){
var seq
$(document).on('click', '#start', function(){
$(this).attr('id','stop');
seq=self.setInterval(function(){blah()},125);
});
$(document).on('click', '#stop', function(){
$(this).attr('id','start');
clearInterval(seq);
});
});
.on()
method允许您附加“正常”非委托(delegate)处理程序或委托(delegate)处理程序,具体取决于您传递给它的参数。
另一个选项是不更改 ID,而仅使用单击处理程序以某种方式测试当前状态:
$(document).ready(function(){
var seq;
$('#start').click(function(){
if (seq) {
clearInterval(seq);
seq = null;
} else
seq=self.setInterval(function(){blah()},125);
});
});
关于javascript - 将函数应用于动态内容 javascript/jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16618694/