[英]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.