i have three divs like that:
<div id="1" >id="1"</div>
<div id="2">id="2"</div>
<div id="3">id="3"</div>
Now i want, whe开发者_运维问答n i click any of the div, jquery will get it id, i.e, if i click div 1, it will get 1 as its div id is 1.
any help will be great.
regards
$(function() {
$('div').click(function() { alert($(this).attr('id')); });
});
or shorter:
$(function() {
$('div').click(function() { alert(this.id); });
});
$("div").click(function() {
var eleId = $(this).attr("id");
}
You can either use delegation or assign a click-handler to each of the divs:
$('#1, #2, #3').click(
function (e) {
alert($(this).attr('id') + ' was clicked');
}
)
If you have a parent container you could use the live
-method to bind a single listener and utilize event delegation:
<div id="parent">
<div id="1" >id="1"</div>
<div id="2">id="2"</div>
<div id="3">id="3"</div>
</div>
$('#parent > div').live('click', function (e) {
alert($(this).attr('id') + ' was clicked');
});
精彩评论