简体   繁体   中英

jQuery only firing once

I got one problem: My jQuery ist only firing once:

<script type="text/javascript">
$(function() {
    $('#delcat').click(function() {
        var elem = $(this);
        var parents = $('.did' + elem.attr('data-catid'));
        var parents2 = $('.did2' + elem.attr('data-catid'));
        $.ajax({
            type: 'get',
            url: 'del_name.php',
            data: 'id=' + elem.attr('data-catid'),
            beforeSend: function() {
                elem.animate({ 'backgroundColor': '#fb6c6c' }, 400);
                parents2.animate({ 'backgroundColor': '#fb6c6c' }, 400);
            },
            success: function() {
                parents.fadeOut("slow");
            }
        });
        return false;
    });
});
</script>  

I can delete only the first "item". After that it needs a refresh and than I can delete the next first "item" again. Very confusing.

This is how the "items" are displayed:

<?  foreach($stmt as $row) { ?>
<div class="col-lg-3 col-xs-6 did<?php echo $row[0]; ?>" id="row1">              
    <div class="small-box bg-aqua">
        <div class="inner did2<?php echo $row[0]; ?>">
            <p>Name</p>
            <h2><? echo $row[1]; ?></h2>
        </div>
        <a href="#" id ="delcat" class="small-box-footer" data-catid="<?php echo $row[0]; ?>" >Delete <i class="fa fa-eraser"></i></a>
    </div>
</div>      
<? } ?>

You can have one unique id on a single page; since you're looping through $stmt , you can't be using id multiple times. Replace the id with a class and bind that

PHP -- Loop

<a href="#" class="delcat small-box-footer" data-catid="<?php echo $row[0]; ?>" >Delete <i class="fa fa-eraser"></i></a>

And JS changes.

$('.delcat').click(function(){
     ....
});

Use class to do that things:

$('.delcat').click(function(){

instead of

$('#delcat').click(function(){

In your html:

<a href="#" class="small-box-footer delcat" data-catid="PHPPART" >Delete <i class="fa fa-eraser"></i></a>

Your solution get the first element with that id. You never have to use multiple equal id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM