我有一些HTML页面,其中包含一个数量不等的缩略图列表(一页上为38),并且我使用以下jQuery在单击时将它们每个的ID属性存储在currPhoto变量中:
$('#thumbnav a:nth-child(1)').click(function() {
currPhoto = $('#0').attr('id');
});
$('#thumbnav a:nth-child(2)').click(function() {
currPhoto = $('#1').attr('id');
});
$('#thumbnav a:nth-child(3)').click(function() {
currPhoto = $('#2').attr('id');
});
$('#thumbnav a:nth-child(4)').click(function() {
currPhoto = $('#3').attr('id');
});
$('#thumbnav a:nth-child(5)').click(function() {
currPhoto = $('#4').attr('id');
});
...等等,继续增加33个。
我确定必须有一种方法可以将其简化为一个代码块,但是我没有使用jQuery的经验,因此我一生都无法解决可能的问题。
因为你看所有的a
下元素#thumbnav
,你并不需要单独选择:
$('#thumbnav a').click(function() {
currPhoto = this.id; // `this` will be the clicked `a` element
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句