Javascript 如何获取已单击的Div的名称?
我正在使用下面的htmlJavascript 如何获取已单击的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
<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&JSid
是唯一的,请勿重复使用。将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;
});
});