javascript 类的 JQuery 单击侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15452875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery click listener for class
提问by Mika H.
I have a class of images in HTML, with IDs img1
,img2
,...,img9
. I want to make links (HTML a
tag) with IDs link_img1
, link_img2
, ..., link_img9
so that whenever I click on a link, the corresponding image appears.
我有一类 HTML 图像,带有 ID img1
, img2
,..., img9
。我想制作a
带有 ID link_img1
、link_img2
、 ... 的链接(HTML标签),link_img9
这样每当我点击链接时,就会出现相应的图像。
I'm thinking about assigning all the links to the same class, then add a JQuery click listener for that class, and inside the listener, look for the ID of that link, and shows the corresponding image. How do I add a JQuery listener for a class, and how do I get the ID from the element?
我正在考虑将所有链接分配给同一个类,然后为该类添加一个 JQuery 单击侦听器,并在侦听器内查找该链接的 ID,并显示相应的图像。如何为类添加 JQuery 侦听器,以及如何从元素获取 ID?
回答by jantimon
You shouldn't use the ids of a
tags to define their target.
Better use the href
attribute instead:
你不应该使用a
标签的 id来定义它们的目标。更好地使用该href
属性:
<img id="img1" ...>
<img id="img2" ...>
<a href="#img1" class="image-link">Click me</a>
<a href="#img2" class="image-link">Click me</a>
jQuery("a.image-link").click(function(){
$(this.href).show();
});
This allows you to have two links for the same image.
这允许您为同一图像有两个链接。
回答by user1032531
To add a listener for a class, just select it the jQuery way (i.e. $('elem.class'). Then use attr() to get the id.
要为一个类添加一个监听器,只需通过 jQuery 方式选择它(即 $('elem.class')。然后使用 attr() 获取 id。
回答by ryan
Here. As mentioned in some other answers, id
is probably not the best way to determine what action you should take. Use another attribute as you see fit
这里。正如其他一些答案中提到的那样,id
可能不是确定应该采取什么行动的最佳方式。使用您认为合适的其他属性
$('a.some-class').click(function() {
switch (this.id) {
case 'one':
// do something
break;
case 'two':
// do something
break;
default:
// do something
break;
}
});
回答by Anujith
Try:
尝试:
$('a.yourClassName').click(function(){
$('img#'+ this.id).show();
});
回答by bipen
try this
试试这个
$('a.yourClass').click(function(){
var $linkID= $(this).attr('id');
$('img#'+ $linkID).show();
});