<div rownumber="0" messageid="29" style="margin:1px 1px 1px 1px; border:1px solid black">
<input type="button" value="Vote" id="vote">
<input type="button" value="Flag" id="flag">
</div>
These <div> elements are added dynamically to my page. How do I bind a Jquery click event to each of these vote and flag buttons and get the rownumber or messageId value from whatever parent <div> the button is in.
Thanks!
First of all, don’t use
idfor those buttons if you’re going to have more than one. An HTML ID means that you can uniquely identify the element by that name, which you can’t if there’s two or more. Instead, makevoteandflagclasses.Next, do this:
I’m assuming you have a JavaScript function called
vote. The important thing is what’s passed to it: that will get the parent of the element that has been clicked on and then get itsrownumberattribute. Usinglivewill ensure that any elements you create after you call it will also have the event bound to it.As an aside, you should probably use
data-row-numberanddata-message-idor something similar for the attributes. HTML doesn’t recommend making up your own attributes randomly: if you prefix them withdata-, they’re guaranteed not to clash with anything. You can then retrieve the information using eitherattras above or jQuery’sdatafunction.