简体   繁体   中英

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. 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. 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.

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.

Example Sudo Code:

<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. 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. 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:

<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:

Working demo: 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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