如何使用jQuery获取clicked元素的ID [英] How to get ID of clicked element with jQuery
问题描述
我有以下html:
<a href="#" id="#1" class="pagerlink" >link</a>
<a href="#" id="#3" class="pagerlink" >link</a>
<a href="#" id="#2" class="pagerlink" >link</a>
/*etc.... */
以及以下jQuery脚本:
and the following jQuery script:
$(document).ready(function() {
var $container = $('.gallery_r').cycle({
fx: 'scrollHorz',
speed: 500,
timeout: 0
});
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id);
return false;
});
});
"pagerlink"链接控件指向jQuery Cycle幻灯片.如果我换成这一行:
the 'pagerlink' links control are to jQuery Cycle slideshow. If I swap this line:
$container.cycle(id);
为此
$container.cycle(7);
它可以工作...(显然仅导航至幻灯片7).因此,我的问题是如何获取点击链接的ID并将其传递给该行?
it works... (obviously only navigating to slide number 7). So, my question is how can I pick up the ID of the link being clicked and pass it into that line?
提前谢谢!
推荐答案
您的ID为#1
,而cycle
只想要一个传递给它的数字.您需要先删除#
,然后再调用cycle
.
Your IDs are #1
, and cycle
just wants a number passed to it. You need to remove the #
before calling cycle
.
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('#', ''));
return false;
});
此外,ID不应包含#
字符,这是无效的(数字ID也是无效的).我建议将ID更改为pager_1
.
Also, IDs shouldn't contain the #
character, it's invalid (numeric IDs are also invalid). I suggest changing the ID to something like pager_1
.
<a href="#" id="pager_1" class="pagerlink" >link</a>
$('a.pagerlink').click(function() {
var id = $(this).attr('id');
$container.cycle(id.replace('pager_', ''));
return false;
});
这篇关于如何使用jQuery获取clicked元素的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!