Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取已单击的Div的名称?_Javascript_Jquery_Css - Fatal编程技术网

Javascript 如何获取已单击的Div的名称?

Javascript 如何获取已单击的Div的名称?,javascript,jquery,css,Javascript,Jquery,Css,我正在使用下面的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

我正在使用下面的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> 
这仅在单击第一个“chatid”Div时给出名称,是否有方法返回任何“chatid”Div的名称

谢谢

此外,不要对多个元素使用相同的ID,因为这是一种不好的做法。改用类


请参见,您的html无效。只能有一个具有给定id的元素

改为使用类:

然后,您的选择器将是:

$(".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>

工作示例不确定是否只是为了示例,但使用多个同名的
id
属性是个坏主意。您的HTML无效,请使用此验证器验证您的HTML:提示:您使用了相同id的2倍,这会导致“崩溃”您的CSS&JS
id
是唯一的,请勿重复使用。将id替换为类并
thread
声明它
var thread
。。。。
$(".chatid").click( //do something );
<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>
    $(document).ready(function() {
  $(".chatid").click(function() {
    var thread = $(this).attr('name');
    //$("#chatmessages").load('fetchmessages.php?id=' + thread);
    alert($(this).attr('name'));
    return false;
  });
});