开发者

jquery always hiding the same div no matter what div I click

I'v built a application using codeigniter and I have a message system that displays the users messages, this is done with a foreach statement. I have some JS in the background that once a user clicks on 'delete' of a specific message that message hides from view while the JS posts the message ID to my controller and marks that message as deleted. What is happening though is that once a user clicks on delete only the first message hides (only the first foreach value) but all other messages have separate ids but are not respondi开发者_JAVA技巧ng to the delete click. I should also note that if I click on 'delete' of any message the first message hides and not the message I clicked on.

heres some code:

View

<?php foreach ($rows as $r) : ?>
<li id="notification_<?php echo $r['MID']; ?>"><?php echo anchor("$r[MID]", 'X', array('class'=>'delete', 'rel'=>"$r[MID]")); ?>
<p>
<?php echo anchor("headless/view_msg/$r[MID]", $r['head'], array('rel'=>'notifications')); ?>
<?php if(strlen($r['body'] >= 74)) : ?>
<?php echo $r['body']; ?>
 <?php else : ?>
<?php echo substr($r['body'], 0, 74) . "..."; ?>
<?php endif; ?>
</p>
</li>
<?php endforeach; ?>

JS:

    $("a.delete").click(function(eve) {
    eve.preventDefault();

    var MID = $("a.delete").attr('rel');

    $.post('headless/notification_read', {
        MID: MID},

    function(html){
        if(parseFloat(html)){

            $('#notification_' + MID).hide('slow')
            console.log('success');

        }else{

            console.log('fail');
        }
    })

});

Im not to sure whats going on here but my guess would be that the javascript is only linking the first foreach and not the rest(if so how would i fix this)

Any help would be appreciated.

Thanks.


$("a.delete").click(function(eve) {
    eve.preventDefault();

    var MID = this.rel; // `this` would be the element being clicked on....
    //var MID = $("a.delete").attr('rel'); this line is the problem....

    $.post('headless/notification_read', {
        MID: MID},

    function(html){
        if(parseFloat(html)){

            $('#notification_' + MID).hide('slow')
            console.log('success');

        }else{

            console.log('fail');
        }
    })
});

demo with comments


it seems you have a collection of anchor links that share the "delete" class, so I think this piece of code would always delete the very first one. You may want to specify the specific index of the anchor, something like

$("a.delete")[x].attr('rel')

where x is the index in this collection.

God I already forget how to program in jQuery after half a year! Sorry no other details could be given.

Edit:

Maybe a better way is to retrieve the unique id user is clicking on and pass its rel to your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜