I am doing an AJAX request with Jquery and PHP what I am doing is looping through an array and producing a table, each loop a new is created and an id is given to it, when they click the read me link the ajax and some more content is returned, on clicking read more I want the associated table row to be removed from the table is this possible, you can see my attempt so far below.
<div id="new" class="tabdiv">
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as 开发者_JAVA百科$row) {
if($row['commentRead'] == 0) {
?>
<tr id="<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
}
} else {
echo "You have no new suggestions";
}
?>
</table>
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $('a.readMore').attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function() {
$('tr').remove()
}
});
return false;
});
You can get the id of the row like this:
$(this).parent().parent().attr("id")
$(this)
wraps the a element, the first parent gets the td and the next one the tr. Call this inside the click callback. Make sure that the id starts with a letter; it is not allowed to start a number. To delete it, define a variable:
var row = $(this).parent().parent();
You can then delete it at the callbacks:
row.delete();
As kgiannakakis points out you'll need a reference to the element that was clicked. To find out what went wrong, consider the following lines of your code:
$('a.readMore').click(function(){
var url = $('a.readMore').attr('href');
...
return false;
});
What you do here is add an event handler to all a elements with a readMore class. When the link is clicked you again select all a elements with a readMore class and retreive the href attribute from the first matched element. What you want to do is get the attribute from the element that was clicked.
$('a.readMore').click(function(){
var url = $(this).attr('href');
...
return false;
});
The same problem occurs in the success and complete handlers of your ajax request, note that you can't use this in the success/complete handlers because it will probably point to another object so you need to store it in a var before calling the ajax function.
精彩评论