将点击绑定到重复的div ID [英] Binding click to a repeated div ID

查看:98
本文介绍了将点击绑定到重复的div ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建div弹出画廊类型的东西.但是我的方法遇到了问题.

I'm trying to create a div popup gallery type thing. But I'm having an issue with my approach.

我有一些链接的缩略图,它们链接到大图像. 这些图像中的每一个看起来都是这样

I have a few linked thumbnail images, which link to the large image. Each of these images looks like so

<a href="www.google.com" id="galImage">
<img src="http://www.savoryspiceshop.com/content/mercury_modules/cart/items/3/0/3/3030/rogan-josh-salt-free-thumbnail-fw232.jpg">
</a>
<br />
<a href="www.yahoo.com" id="galImage">
<img src="http://www.savoryspiceshop.com/content/mercury_modules/cart/items/2/9/8/2986/italian-herbs-salt-free-thumbnail-fw232.jpg">
</a>

如您所见,每个都有相同的ID"galImage".我不想为每个对象创建一个单独的ID,因为有时可能有2张图片,有时可能有20张图片.所以只是想简单地检查一下是否看到#galImage被点击就可以运行一些jquery.

As you can see, each has the same id of "galImage". I didnt want to create a separate ID for each as sometimes there might be 2 image and sometimes there might be 20. So just thought simply checking to see if #galImage get's clicked i'd run some jquery.

我的问题是,只有#galImage的第一次出现才触发jquery,其他所有实例都将失败.

My issue is, that only the very first occurence of #galImage triggers the jquery, every other instance fails.

这是上面示例的JSfiddle. http://jsfiddle.net/MH6eJ/1/ 单击图像1,它起作用.但是图片2失败了.

Here's a JSfiddle with the above example. http://jsfiddle.net/MH6eJ/1/ Click image 1, it works. But image 2 fails.

我该怎么做?

推荐答案

根据文档,您的id在页面中确实是唯一的.如果您想拥有更多具有该样式的HTML元素(例如),请使用class.

According to documentation, your id has do be unique in the page. If you want to have more HTML elements with that style (for exapmle), use class.

id = name [CS]:

此属性为元素分配名称.此名称在文档中必须是唯一的.

This attribute assigns a name to an element. This name must be unique in a document.

class = cdata-list [CS]:

此属性为一个元素分配一个类名或一组类名.可以为任何数量的元素分配相同的一个或多个类名.多个类名必须用空格字符分隔.

This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

<a href="www.google.com" class="galImage">
<img src="http://www.savoryspiceshop.com/content/mercury_modules/cart/items/3/0/3/3030/rogan-josh-salt-free-thumbnail-fw232.jpg">
</a>
<br />
<a href="www.yahoo.com" class="galImage">
<img src="http://www.savoryspiceshop.com/content/mercury_modules/cart/items/2/9/8/2986/italian-herbs-salt-free-thumbnail-fw232.jpg">
</a>

然后,当您使用jQuery选择要使用$(".galImage")的类时.

Then when you select with jQuery that class you use $(".galImage").

$('.galImage').click(function(e){
    e.preventDefault();
    alert($(this).attr("href"));
});

更新了您的 jsFiddle .

这篇关于将点击绑定到重复的div ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆