[英]How do I get the name of a Div that has been clicked?
I am using the following html 我正在使用以下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 我正在使用以下jQuery脚本
$(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? 这仅在单击第一个“ chatid” Div时给出名称,我是否可以返回任何“ 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. 此外,请勿对多个元素使用相同的ID,因为这是不好的做法。 Use classes instead. 改用类。
See Why is it a bad thing to have multiple HTML elements with the same id attribute? 请参阅为什么具有多个具有相同id属性的HTML元素是一件坏事?
You have invalid html. 您的HTML无效。 There can be only one element with given id. 具有给定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 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 is 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.