想让jquery执行多个动作,还是有另一种方式

Building off a previous question,

Is it possible to make a jquery button do two things at once? Right now I have this:

<td>
 <a href="#'.$row['abstractid'].'">
   <button onClick="$(\'.hide\').toggle();">Read Abstract
   </button>
 </a>
</td>

This works (yay!) - it both jumps to and displays the div that is hidden with that database id number- but since those results are looped, it displays ALL of them. Now, it goes to the correct place on the page, but it still shows all the results instead of just that one result.

Could I make this button so onClick it not only toggles the hide but also sets the database ID number for the query to pull so it only displays one set of results- OR just only displays that one database ID set and leaves the others hidden? Would I have to set the table id as the database id and give that the class of hidden instead of putting it into a div?

Example: right now it's:

<div id="'.$row['abstractid'].'" style="display:none;" class="hide">
<table>
stuff
</table>

But would I need to make it

<table id="'.$row['abstractid'].'" style="display:none;" class="hide">

instead? This makes sense to me in theory but I'd have to be a little creative with my CSS I think.

  1. You toggle all items with the class "hide" instead of only the specific one
  2. You don't need to put a button into an anchor (I don't even know if it's allowed). If you need it to look like a button you can use CSS.
  3. IDs have to start with a letter and not with a number. I guess your abstractid is a number, therefore I prepended abstr
  4. If you give an element the class hide (which presumably hides it) then you don't really need the inline style.

Here is the updated code:

<a href="#abstr'.$row['abstractid'].'" onclick="$(\'#abstr'.$row['abstractid'].'\').toggle()">Read Abstract</a>

<table id="abstr'.$row['abstractid'].'" class="hide">

You could use onclick="function() {$(\'.hide\').toggle();$(\'.hide\').toggle();}"

However, I would not recommend that. My suggestion is:

<button class="read-abstract">Read Abstract</button>

Then

<script>
$(document).ready( function() {
    $(".read-abstract").live( "click", function() {
        // do stuff here
    });
}
</script>

For more on unobtrusive Javascript: http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

Regarding showing and hiding values I always approach it as so:

HTML:

<button data-hide-id="1" class="read-abstract">Read Abstract</button>
<table id="table-1" class="hide">
    <tr>
        <td>Contents will show hide on click of read abstract</td>
    </tr>
</table>

JS (in <head>):

<script type="text/javascript">
$(document).ready( function() {
    $(".read-abstract").live( "click", function() {
        $("#table-" + $(this).data("hide-id") ).toggle();
    });
}
</script>

Working example: http://jsfiddle.net/sZREt/