Reputation: 41685
Suppose you have a list of posts and each post has an id.
Now there can be many buttons, fields, etc to interact with this post.
(edit/delete/upvote/title .. to name a few)
I've included id in every element that is interactive and used it to reference other elements. (e.g. when user clicks an edit button, I find textarea with the same id to change the appearance)
<div class='post' data-post-id='3'>
<div class='upvote' data-post-id='3'>
{{upvote}}
</div>
<div class='textarea' data-post-id='3'>
</div>
<div class='buttons'>
<button class='btn-edit' data-post-id='3' />
<button class='btn-delete' data-post-id='3' />
<button class='btn-upvote' data-post-id='3' />
</div>
</div>
I'm fairly new to javascripts and feels this awkward.
Are there better scheme (or strategy) to give identifiers to work with?
Upvotes: 0
Views: 85
Reputation: 2557
a simpler approarch will be like so
<div class='post' data-post-id='3'>
<div class='upvote'>
{{upvote}}
</div>
<div class='textarea'>
</div>
<div class='buttons'>
<button class='btn-edit' />
<button class='btn-delete' />
<button class='btn-upvote'/>
</div>
</div>
now when the user clicks the button you can do as follows :
$('button').click(function(){
console.log($(this).parents('.post').data('post-id'))
})
so when you apply the edit it will be like so
$('div[data-post-id="3"].textarea')
sure thing you will need to replace the "3" with the id you got from the previous function .
as T.J. Crowder said you can use closest . if you feel that parents is an over kill .
Upvotes: 1
Reputation: 1074355
I would just put the data-post-id
on the post's top-level div
(with class post
). Then, any time you need it, if your starting point is one of the elements within that div
, just use closest
to find it, e.g. suppose this
is one of the buttons. Then:
var postId = $(this).closest("div.post").attr("data-post-id");
So for instance, I assume all of these posts are in a container of some kind, which I'll call div.container
. You can use a delegated handler for your various buttons, like so:
$("div.container").on("click", ".btn-edit", function() {
var postId = $(this).closest("div.post").attr("data-post-id");
// ...handle the edit click
});
Side note: I've used .attr("data-post-id")
to retrieve the post ID above. You'll get a lot of people telling you to use .data("post-id")
. While that works, it's overkill unless you're going to do other things with the data. The .data
method manages data associated with the element using off-element storage managed by jQuery, and initializes that data from the data-*
attributes. If your only use of the data-*
attribute is to read it, .data
is overkill. Mostly harmless, but overkill.
Upvotes: 2
Reputation: 1626
You can use jquery selectors http://api.jquery.com/category/selectors/ to find appropriate element. For example:
$("#element") will get you element with id="element" (eg: )
in your case you can use
$(".btn-edit").click(function(){
// action
});
Upvotes: -1