Avoiding inline JavaScript with dynamic content
<p>I read <a href="http://coding.smashingmagazine.com/2008/09/16/jquery-examples-and-best-practices/" rel="nofollow">here</a> that you should avoid coding JavaScript inline (see item #1).</p>

<p>It sounds like a great idea; however, I'm not sure how to use js to select dynamic content without setting the id in the function call inline.</p>

<p>For example, I have a simple blog. The comments are hidden, but can be displayed by clicking an anchor (generated dynamically) that calls a JavaScript function to toggle the comments for that specific post:</p>

<pre><code>$commentsButton = "&lt;a name='comments" . $post-&gt;id . "' href='#comments" . $post-&gt;id . "'&gt; comments (" . count($comments) . ")&lt;/a&gt;";
</code></pre>

<p><code>toggleComments()</code> function:</p>

<pre><code>function toggleComments(id) {
    $('#' + id + ' .commentsContainer').toggle(500);
}
</code></pre>

<p>How do you keep from doing this kind of thing? Is it always appropriate to avoid inline JavaScript? Or is this a case where it's necessary?</p>

<p><strong>Update:</strong></p>

<p>I ended up using this:</p>

<pre><code>$('.commentButton').each(function() {
    $(this).click(function() {
        $(this).parents('.post').find('.commentsContainer').toggle(500);
    });
});
</code></pre>

<p>with this:</p>

<pre><code>$commentButton = "&lt;a class='commentButton'&gt; comments (" . count($comments) . ")&lt;/a&gt;";
</code></pre>
