簡體   English   中英

如何獲得已單擊的Div的名稱?

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

我正在使用以下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> 

我正在使用以下jQuery腳本

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

這僅在單擊第一個“ chatid” Div時給出名稱,我是否可以返回任何“ chatid” Div的名稱?

謝謝

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

此外,請勿對多個元素使用相同的ID,因為這是不好的做法。 改用類。

請參閱為什么具有多個具有相同id屬性的HTML元素是一件壞事?

您的HTML無效。 具有給定ID的元素只能是一個。

使用類代替:

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

那么您的選擇器將是:

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

id是唯一的,請勿重復使用

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

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

工作示例在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM