【发布时间】:2012-10-03 09:21:39
【问题描述】:
我想循环我的点击事件,以使代码更短。以后我可能会有 30 个这样的值。
我的工作代码
$(document).ready(function () {
var last_click = '';
$("#title").click(function() { last_click = 'title'; });
$("#subtitle").click(function() { last_click = 'subtitle'; });
$("#test").click(function() { last_click = 'test'; });
});
这就是我想要的(不工作)
我的猜测是,每个循环都在 dom 就绪状态下运行,然后再也不会,这样点击事件就永远不会被触发?
$(document).ready(function () {
var last_click = '';
var contents = new Array();
contents = ['title', 'subtitle', 'test'];
$.each(contents , function(index, value){
$("#" + value).click(function() { last_click = value; });
});
});
如果没有像我想的那样解决,我会感谢一个很好的解决方法。
【问题讨论】:
-
你有什么应该工作..触发点击事件是什么意思?您正在将 click 事件绑定到
contents中的元素列表。 -
附注:
contents中的new Array()在下一行被另一个数组破坏;不需要。 -
你的代码对我有用:jsfiddle.net/barmar/rS2Gb/6
标签: javascript jquery arrays click each