2011-01-25 65 views
1

我有代碼,所以當你點擊一個單詞時,它被替換爲另一個單詞。當我需要重複執行該操作時,如何綁定到單擊事件中的點擊事件?

<script> 
    $(document).ready(function() { 
     $('.note_text').click(function(){ 
      $(this).remove(); 
      $('#note_div').append('<span class="note_text">new</span>'); 
      // re-applying behaviour code here 
     }); 
    }); 
</script> 

<div id="note_div"> 
    <span class="note_text">preparing</span> 
</div> 

我需要附加單詞具有相同的點擊行爲。做這個的最好方式是什麼?

+0

您的樣品我只看到文字改變......爲什麼不改變這種狀況呢? – 2011-01-25 10:47:15

回答

2

變化

$('.note_text').click(function(){ 

$('.note_text').live('click',function(){ 

這將導致你的頁面,不斷獲取類的note_text'有行爲,通過.live

0

你可以重新綁定設置上的任何東西處理者:

function handler(){ 
    $(this).remove(); 
    $('#note_div').append("<span class="note_text">new</span>"); 
    $(".note_text").unbind("click"); 
    $('.note_text').click(handler); 
} 

$(document).ready(function() { 
    $('.note_text').click(handler); 
}); 
2

您應該使用一個.live()help.delegate()help爲此目的的綁定。

$(function() { 
    $('#note_div').delegate('.note_text', 'click', function(e) { 
     $(e.target).parent().append("<span class='note_text'>new</span>").end().remove(); 
    }); 
}); 

演示http://www.jsfiddle.net/PkngP/2/

相關問題