简体   繁体   English

使用jQuery'this'与多个元素的选择器

[英]Using jQuery 'this' with a selector of multiple elements

Sorry jQuery noob question here, I am attempting to make all of the div elements with the class .thumbnail clickable with a callback function. 抱歉,jQuery noob问题在这里,我正在尝试通过回调函数使所有带有.thumbnail类的div元素可单击。 But, once one of the div(s) of that class is clicked I need the specific ID of that given div so I can do further manipulation to that specific one. 但是,一旦单击该类的div之一,我就需要该给定div的特定ID,这样我就可以对该特定div进行进一步的操作。 I am confused if I would use 'this' to reference that specific div once it is clicked or if I am looking at this the wrong way. 如果单击后会使用“ this”来引用该特定的div,或者我以错误的方式查看,我会感到困惑。

Im sure this is a very simple question for you jQuery gurus to answer, its been a long day and my brain is completely zombified. 我确定这是一个非常简单的问题,jQuery专家需要回答,这是漫长的一天,我的大脑完全僵化了。

Example Sudo Code: 示例Sudo代码:

<script>
$(document).ready(function() {

    $(".thumbnail").click(function() {

        //need to get id of thumbnail that was clicked, this is where I am confused       
        var thumbnail_id = $(this).attr('id')
        alert(thumbnail_id);

     });

});

</script>

<div class=thumbnail" id="1">Tom</div>
<div class=thumbnail" id="2">Jerry</div>
<div class=thumbnail" id="3">Sue</div>
<div class=thumbnail" id="4">Mary</div>
<div class=thumbnail" id="5">Brian</div>

你不觉得缩略图应该这样写"thumbnail" ,而不是thumbnail"

It is unclear what your jQuery problem is. 目前尚不清楚您的jQuery问题是什么。 To address the question you're asking, when an object is clicked in your code, the click handler will be called and this will be set to the DOM element that was clicked on. 为了满足你的要求,当单击您的代码的对象的问题, click处理程序将被调用, this将被设置为被点击的DOM元素。 This works if there is one object with the thumbnail class or many. 如果存在一个或多个缩略图类的对象,则此方法有效。

If your problem is really that your HTML is in error, then you should add the missing quote to change this: 如果您的问题确实是您的HTML错误,则应该添加缺少的引号来更改此内容:

<div class=thumbnail" ...

to this: 对此:

<div class="thumbnail" ...

FYI, a better way to do this is as follows. 仅供参考,一种更好的方法如下。 This fixes the quote problem and uses a data attribute rather than a numeric id value: 这可以解决报价问题,并使用数据属性而不是数字id值:

Working demo: http://jsfiddle.net/jfriend00/8tczB/ 工作演示: http : //jsfiddle.net/jfriend00/8tczB/

<script>
$(document).ready(function() {
    $(".thumbnail").click(function() {
        //need to get id of thumbnail that was clicked, this is where I am confused       
        var thumbnail_id = $(this).data('id');
        alert(thumbnail_id);
     });
});
</script>

<div class="thumbnail" data-id="1">Tom</div>
<div class="thumbnail" data-id="2">Jerry</div>
<div class="thumbnail" data-id="3">Sue</div>
<div class="thumbnail" data-id="4">Mary</div>
<div class="thumbnail" data-id="5">Brian</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM