views:

73

answers:

3

Howdy,

i think iam going crazy ..

I have an webpage where iam displaying news comments dynamicly , the "Comment" link is connected to an JQuery function wich is displaying the comments for the news (..like show comments from news id = x)

But "onClick" handlers arent the best way or?

Thats my code in the moment :

                echo  '<li>';
                echo "<a href='#' onClick='showhideComments({$news['id']});'>" .
                         $this->translate('INDEX_COMMENTS'). " ($count)". "</a>";
                echo '</li>';

Any suggestions ? (the link part is running an an foreach loop to set the right id)

+3  A: 

Inline event handlers work. They are just a bad design decision for very large client applications, but there's nothing wrong with using them if you use them properly (ex. return false;).

To answer your question, you can remove them by doing something like:

<script>
$(document).ready(function(){
    $(".comment").click(function(e){
        var news_id = $(this).attr("news_id"); // you can use the news_id for whatever you want
        if(this.style.display == "none")
            $(this).show();
        else
            $(this).hide();
        e.preventDefault();
    });
});
</script>

<?php
echo  '<li>';
echo "<a href='#' class='comment' news_id='".$news['id']."'>" .
$this->translate('INDEX_COMMENTS'). " ($count)". "</a>";
echo '</li>';
?>
Luca Matteis
+2  A: 

how about this:

 echo  '<li>';
 echo "<a href='#' class='comments' name='$count'>" .
  $this->translate('INDEX_COMMENTS'). " ($count)". "</a>";
 echo '</li>';

(i dont know php, so syntax may be wrong)

jquery:

$(".comments").click(function(){
  var id = $(this).attr("name");
  //show the news item for this id
});
mkoryak
I think you meant to put name='{$news['id']}' as the jQuery function takes a news id. But +1 for concept.
Jab
+1  A: 

you can add an attribute and use that to link.

 echo  '<li>';
 echo "<a href='#' id='news_".$news['id']."'>" .
 $this->translate('INDEX_COMMENTS'). " ($count)". "</a>";
 echo '</li>';

Then with jQuery loop through the links and bind the function (http://docs.jquery.com/Events/bind)

$("li > a").bind("click", function(){
   showhideComments($(this).attr("id").split("_")[1]);
});
Josh