当单击链接时不会更新ID

3
我有一个函数用于创建请求到另一个文件以更新数据库:
$('#thumb-up').live('click', function() {
    $('#loading').show();

    $.ajax({
            context: this,
            type: 'GET',
            url: '/gallery/configurations/required/photo-thumbs.php',
            data: 'i=21&t=1',
            success: function() {
                                  $('#loading').hide();
                                  $(this).attr('id', 'thumbup-undo').text('Sluta gilla');
                                  $('#thumbup-count').load('/gallery/configurations/required/thumbup-count.php?i=21&t=1');
                                 }
    });
});

$('#thumbup-undo').click(function() {
    alert('das');
});

当我点击ID为thumb-up的链接时,预期的文本会变成“Sluta gilla”。当我现在点击此链接后,相同a标签的ID将从thumb-up更改为thumbup-undo并显示警报“dsa”。问题在于它没有出现!我甚至不知道它是否更改为thumbup-undo,但我希望它没有。

您可以在这里尝试代码(我已缩短了代码以使演示正常工作)。

我该如何解决这个问题?

提前致谢

4个回答

2
请尝试此演示:http://jsfiddle.net/kxLzu/ 我使用了.prop.on来绑定点击事件,然后在成功时告诉foo这个点击存在。
希望能帮到您 :)
请注意:.live已被弃用,应改用.on代码
    $('#thumb-up').click(function() {
        $.ajax({
                context: this,
                type: 'GET',
                success: function() {
                       $(this).prop('id', 'thumbup-undo').text('Sluta gilla');
                      foo();
                                     }
        });
    });

function foo(){
    $('#thumbup-undo').on('click', function() {
        alert('das');
    });
}
​

非常感谢你的回答 :) 多亏了你,我的问题现在已经解决了。我会尽快接受你的回答 :) - Airikr

2
$('body').on('click','#thumb-up', function() {
    $('#loading').show();

    $.ajax({
            context: this,
            type: 'GET',
            url: '/gallery/configurations/required/photo-thumbs.php',
            data: 'i=21&t=1',
            success: function() {
                                  $('#loading').hide();
                                  $(this).attr('id', 'thumbup-undo').text('Sluta gilla');
                                  $('#thumbup-count').load('/gallery/configurations/required/thumbup-count.php?i=21&t=1');
                                 }
    });
});

$('body').on('click','#thumbup-undo', function() {
    alert('das');
});

在页面加载后,DOM中添加了一个“新”元素,因此您必须使用ON。请记住,.live在最新版本的Jquery中已过时。


那甚至比Tats_innit的解决方案更好!非常感谢!:D - Airikr
不客气 :). 顺便说一下,你可以将“body”替换为一个容器,该容器包含#thumb-up和#thumbup-undo。我使用了body,因为我不知道这是否适用于您的情况。 - Nicolás Torres

0
问题在于,在赋值时, $(“#thumbup-undo”) 不存在。 它只会在稍后创建。
您可以通过使用.live() 来解决此问题,例如 this updated Fiddle

我的天啊,我居然在使用jQuery回答问题?我到底怎么了……通常我会建议不要使用jQuery,并提供一个完整的原生JS答案……这也说明了因为在SO上过度暴露而不得不勉强学习多少东西,哈哈! - Niet the Dark Absol
请记住,.live已经被弃用,建议使用.on。 - Nicolás Torres

0
使用 .on代替 .click()(因为在您的示例中存在这个问题:#thumbup-undo 在创建单击处理程序时不存在),并且还要使用 .live() (因为live()已经在Jquery 1.7中被弃用)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接