I want to get an id as a string of a div that was clicked. is it possible to do?
HTML
<div id="test">
<div class='button' id="a" ><p>Click 1</p></div>
<div class='button' id="b" ><p>Click 2</p></div>
<div class='button' id="c" ><p>Click 3</p></div>
<div class='button' id="d" ><p>Click 4</p></div>
</div>
I can do something like this:
$("#a").click(function() {
/* do some action with this div */
});
But I want to detect the id of just clicked div, because I will have a lot of divs like this, and it doesn't make sense to rewrite the same code over and over again.
I want to get an id as a string of a div that was clicked. is it possible to do?
HTML
<div id="test">
<div class='button' id="a" ><p>Click 1</p></div>
<div class='button' id="b" ><p>Click 2</p></div>
<div class='button' id="c" ><p>Click 3</p></div>
<div class='button' id="d" ><p>Click 4</p></div>
</div>
I can do something like this:
$("#a").click(function() {
/* do some action with this div */
});
But I want to detect the id of just clicked div, because I will have a lot of divs like this, and it doesn't make sense to rewrite the same code over and over again.
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Jan 22, 2013 at 21:38 VorVor 35.3k46 gold badges141 silver badges196 bronze badges 2- 1 Although your HTML is fine, I think I'd choose another class name for your divs: IMO, 'button' can be confusing. – frenchie Commented Jan 22, 2013 at 21:41
- 1 Also, I don't think you need to have a <p> tag inside your divs; just put the text directly inside the div. As a general rule, when you have a box inside a box (think of tags as boxes) you can probably simplify the HTML by removing the inner box and apply the css of the inner box to the outter box. – frenchie Commented Jan 22, 2013 at 22:09
3 Answers
Reset to default 5$("#a").click(function() {
var id = this.id;
});
If you need to set click
event for all .button
elements, here is the short way:
$(".button").click(function(e) {
var id = this.id; // or e.target.id;
});
$("div.button").click(function() {
console.log(this.id);
});
$(this).attr('id')
will get you the id, But if you want to access the div you can use
$(this).parent('div')
this will only return if the immediate parent is a div, if want to find up you can use
$(this).parents('div')
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745568392a4633532.html
评论列表(0条)