![](/img/trans.png)
[英]How do I add a counter to show how many times a div element has been clicked?
[英]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,因为这是不好的做法。 改用类。
您的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.