Question

I'm modifying Flask MiniTwit example to implement twitter-like message reply system, each message has a 'reply' button. I'd like to expand a new div to display replies as well as an input area When a 'reply' button for a specified message was clicked. but now I don't know how to define the 'reply' button in my jinja template.

current my code is like following:

<a href=# data-messageid="{{message._id}}" id="reply">
Reply
</a>

so how to differentiate each 'reply' hyperlink button in my jQuery code?

Was it helpful?

Solution

<div class="replymessage" id="message{{message._id}}">content</div>
<a href="#message{{message._id}}" class="reply">Reply</a>


$('.reply').click( function () {
    var item =  $(this).attr('href');
    $(item).slideToggle(300);
 });

Demo Here

Basically you use the dynamic id number in the href of the button, then in the ID for the corresponding div. This way when you click a link with the href, the div with the same ID opens.

OTHER TIPS

Your current template will result in an invalid HTML document (assuming the template is expanded more than once): id values must be unique in the document, so you can't just have "reply" as the id.

I'd probably change "reply" from an id to a class. Then you can hook them all directly:

$("a.reply").click(function(event) { ... });

...or using delegation:

$("container_for_replies").delegate("a.reply", "click", function(event) { ... });

(Using jQuery 1.7 and up, you can use on instead of delegate; note that the order of arguments is different.)

Within your event handler, this will refer to the specific a element that was clicked, so you can (for instance) get your data-messageid attribute like this:

var messageid = $(this).attr("data-messageid");

...and do anything else you like with the structure around the reply link.

First of all, since the 'reply' button appear with each message, do not use id="reply". class="reply" will be better.

And I think this is what you want:

<a href=# data-messageid="1" class="reply">Reply</a>
<a href=# data-messageid="2" class="reply">Reply</a>
<script type="text/javascript">
    $().ready(function () {
        $('.reply').click(function (argument) {
            alert($(this).attr('data-messageid'));
        });
    });
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top