JS: Counter decrease, at hide()
If I have a normal
<?php echo "Today (".mysql_num_rows($query)."); ?>
That turns out as Today (10) if there's 10 rows.
Now under this counter I have an while() that outputs all the rows inside a <tr>
.
In a <td>
inside the tr i have this delete button, which hides closest 'tr'.
How can I when you hide the 'tr' the Today(10) will decrease to Today(9) ?
--
I dont think its possible with the current counter (mysql_num_rows), but maybe if you count how many 'tr' there is, in the Today(), you could make something th开发者_如何学运维at decreases, but I do not know how to do this. Although this is just an thought..
Alter your PHP accordingly:
<?php echo 'Today (<span class="counter">' . mysql_num_rows($query) . '</span>)'; ?>
And have something like this for your delete button:
$('#theTable').delegate('button.delete', 'click', function (event) {
$(this).closest('tr').slideUp();
$('span.counter').text(function (index, val) {
return (parseInt(val, 10) - 1);
});
event.preventDefault();
});
Note the use of delegate
: It's much more efficient than it would be to bind
an event handler to each delete button.
You'll have to alter the selector for your table and your delete button accordingly.
you can do something like this :
$('.deleteButton').click(function() {
var curn = parseInt($('.counter').text(), 10);
if(curn - 1 >= 0)
$('.counter').text(curn - 1);
});
and change your echo to
<?php echo "Today (<span class='counter'>".mysql_num_rows($query)."</span>)"; ?>
Wrap the number so you can select is easily:
<?php echo 'Today (<span id="number">'.mysql_num_rows($query).'</span>)'; ?>
Then when a delete button is clicked:
// Get the number element once
var num = $('#number');
// Set an onclick event on your button
$('.delete').click(function(){
// Find the closest table row and remove it
$(this).closest( 'tr' ).remove();
// num.text() will get the text inside the number element
// parseInt is used to convert it from string to int
// subtract 1 to update the number
var newNumber = parseInt( num.text(), 10 ) - 1;
// And set the new number text
num.text( newNumber );
// Stop the default browser action - might cause the page to reload or to scroll
return false;
});
try it at: http://jsfiddle.net/xMZgv/7/
Today(<span id="counter">3</span>)
<table>
<tr><td>hello</td><td>delete</td></tr>
<tr><td>world</td><td>delete</td></tr>
<tr><td>hi</td><td>delete</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.js"></script>
<script>
$(function() {
$('table tr').find('td:last').click(function() {
$(this).parent().remove();
$('#counter').html($('#counter').html() - 1)
})
})
</script>
Output your counter to a JavaScript var and use it in your loop and Today() function call. I'm assuming you're trying to output a client side function call from the server?
<?php echo "var count=".mysql_num_rows($query).";Today(count);" ?>
In your delete handler decrement count and call Today(count) again.
精彩评论