Jquery 单击时不会更新链接的ID
我使用此函数创建对另一个文件的请求以更新数据库:Jquery 单击时不会更新链接的ID,jquery,Jquery,我使用此函数创建对另一个文件的请求以更新数据库: $('#thumb-up').live('click', function() { $('#loading').show(); $.ajax({ context: this, type: 'GET', url: '/gallery/configurations/required/photo-thumbs.php', data: 'i=
$('#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
更改为thumb up undo
,并显示警报“dsa”。这里的问题是它没有出现!我甚至不知道它是否会变为thumbup undo
,但我希望它不会
您可以尝试代码(我缩短了代码以使演示正常工作)
我如何解决这个问题
提前感谢问题是,在分配任务时,
$(“#拇指朝上撤消”)
不存在。它只在以后创建
您可以使用.live()
解决此问题,如。使用而不是.click()
(因为这就是您的示例中的问题:#在创建单击处理程序时,不存在“拇指朝上撤消”
)也不要使用
.live()
(因为live()
是)。请尝试此演示
我已使用.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');
});
}
您必须使用ON,因为页面加载后会向dom添加一个“新”元素。记住,live在最新版本的Jquery中被弃用了天哪,我真的要在Jquery中给出答案吗?发生在我身上的事。。。通常我建议不要使用jQuery,而是用原始JS提供完整答案。。。也去显示我有多么不情愿地学习,由于过度曝光,所以,哈哈!记住。live不推荐使用,您应该建议使用。谢谢您的回答:)多亏了您,我的问题现在已经解决了。我会尽快接受你的回答:)很高兴我能帮助@ErikEdgren:)!这甚至比塔斯尤因尼特的解决方案更有效!非常感谢欢迎你:)。顺便说一句,您可以将“body”替换为包含“thumb up”和“thumb up undo”的容器。我用了body bc我不知道这是不是你的案子。
$('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');
});