简体   繁体   中英

How do I get the name of a Div that has been clicked?

I am using the following html

<div id="chatid" name="1">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> John
</div>
<div id="chatid" name="2">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> James
</div> 

I am using the following jquery script

$(document).ready(function() {
  $("#chatid").click(function() {
    thread = $(this).attr('name');
    $("#chatmessages").load('fetchmessages.php?id=' + thread);
    //alert($(this).attr('name'));
    return false;
  });
});

This only gives the name when clicking on the first "chatid" Div, is there a way for me to return the name of any "chatid" Div?

Thanks

$('div').click(function(){
    alert($(this).attr('name'));
});

Additionally, do not use the same ID for multiple elements as this is bad practice. Use classes instead.

See Why is it a bad thing to have multiple HTML elements with the same id attribute?

You have invalid html. There can be only one element with given id.

Use class instead:

<div class="chatid" name="1">

then your selector will be:

$(".chatid").click( //do something );

id is unique don't use repeatedly

<div class="chatid" name="1">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> John
</div>
<div class="chatid" name="2">
  <img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle" /> James
</div>

JavaScript is

    $(document).ready(function() {
  $(".chatid").click(function() {
    var thread = $(this).attr('name');
    //$("#chatmessages").load('fetchmessages.php?id=' + thread);
    alert($(this).attr('name'));
    return false;
  });
});

Working example is Here

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