我有这个函数来创建另一个文件的请求来更新数据库:
$('#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”。当我现在点击此链接时,同一标记的ID将从thumb-up
更改为thumbup-undo
,并且会显示警告“dsa”。这里的问题是它没有出现!我甚至不知道它是否改为thumbup-undo
但我希望它不会改变。
您可以尝试代码here(我已缩短代码以使演示正常运行)。
如何解决此问题?
提前致谢
答案 0 :(得分: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');
});
}
答案 1 :(得分: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');
});
您必须使用ON,因为在页面加载后将dom中添加了“new”元素。记得.live在最新版本的Jquery
中已被弃用答案 2 :(得分:0)
问题在于,在分配时,$("#thumbup-undo")
不存在。它只是稍后创建的。
您可以使用.live()
处理此问题,如this updated Fiddle。
答案 3 :(得分:0)
使用.on代替
.click()
(因为这是您示例中的问题:创建点击处理程序时#thumbup-undo
不存在)
而且{而不是.live()
(因为live()
是deprecated in jquery 1.7)。