事件不会在for循环中添加
这是html。 如果单击一个链接,我想用一些文本替换它前面的span元素。
that1 Update1
that2 Update2
that3 Update3
that4 Update4
that5 Update5
正如你所看到的,我的想法是给锚点提供相同的id和数字。
在我的jquery-code中,我循环遍历所有的anchor元素,给它们一个click事件,导致它前面的span-element被替换。
$(document).ready(function() { var numSpans = $("span").length; for (n=0;n<=numSpans;n++) { $("a#update" + n).click(function(e){ $('span#sp' + n).replaceWith('this'); e.preventDefault(); }); } });
出于某种原因,这不起作用。
我究竟做错了什么?
原始代码的问题在于您在变量n
上创建了一个闭包。 调用事件处理程序时,在调用点调用它的值为n
,而不是声明点。 你可以通过添加一个警报调用来看到这个:
$(document).ready(function() { var numSpans = $("span").length; for (n = 1; n <= numSpans; n++) { $("a#update" + n).click(function(e) { alert(n); //Alerts '6' $('span#sp' + n).replaceWith('this'); e.preventDefault(); }); } })
解决这个问题的一种方法是在每次迭代中创建一个n值的闭包,如下所示:
$(document).ready(function() { var numSpans = $("span").length; for (n = 1; n <= numSpans; n++) { $("a#update" + n).click( (function(k) { return function(e) { alert(k); $('span#sp' + k).replaceWith('this'); e.preventDefault(); } })(n) ); } })
但是,这很麻烦,你最好使用更多的jQuery-y方法。
一种方法是从代码中删除id
。 除非你需要其他东西,否则他们不需要:
that1 Update1
that2 Update2
that3 Update3
that4 Update4
that5 Update5
jQuery的:
$(function() { $('a.update').live('click', function() { $(this).siblings('span').replaceWith("Updated that!"); }); });
的jsfiddle
不要在循环中创建函数。 使用jQuery,根本不需要显式循环。
$(function() { $('span[id^=sp]').each(function(n) { $('#update' + n).click(function(e) { $('#sp' + n).replaceWith(this); return false; }); }); });
演示: http : //jsfiddle.net/mattball/4TVMa/
不过,你可以做得更好:
$(function() { $('p > a[id^=update]').live('click', function(e) { $(this).prev().replaceWith(this); return false; }); });
演示: http : //jsfiddle.net/mattball/xySGW/
试试这个:
$(function(){ $("a[id^='update']").click(function(){ var index = this.id.replace(/[^0-9]/g, ""); $("span#sp" + index).replaceWith(this); e.preventDefault(); }); });