2012-06-15 48 views
3

我有這個函數創建到另一個文件的請求來更新數據庫:不會爲上點擊一個鏈接更新ID

$('#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(我縮短了代碼以使演示正常工作)。

我該如何解決這個問題?

在此先感謝

回答

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。請記住.live在最新版本的jQuery中已棄用

+0

這甚至比Tats_innit的解決方案效果更好!非常感謝! :D – Erik

+0

不客氣:)。順便說一句,你可以替換容器的'body'來容納#thumb-up和#thumbup-undo。我用身體bc我不知道這是你的情況。 –

0

的問題是,在轉讓時,$("#thumbup-undo")不存在。它只在以後創建。

您可以使用.live()來解決此問題,如this updated Fiddle

+0

我的上帝,我是否認真地給jQuery中的答案?發生在我身上的事情......通常我會建議不要使用jQuery,並在原始JS中提供完整的答案......還會顯示我因爲過度暴露於SO,LOL而不情願地學習了多少! –

+0

記住.live已棄用,建議您使用.on –

0

使用.on而不是
.click()(因爲這是在你的榜樣的問題:當您創建點擊處理程序#thumbup-undo不存在)
也代替.live()(因爲live()deprecated in jquery 1.7)。

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'); 
    }); 
} 
​ 
+0

非常感謝您的回答:)我的問題現在已經解決了,謝謝您。我會盡快接受你的回答:) – Erik

+0

很高興我可以幫助@ErikEdgren :)! –