2013-01-07 25 views
7

我有這個簡單的代碼。 http://jsfiddle.net/borth/BmEZv/ 如果您點擊鏈接一次,它工作正常。如果你再次點擊它,它不起作用。由於在DOM加載後html被加載到html中,我試過.on,.bind,.delegate和.live。他們沒有工作,除了.live被棄用(我正在使用jQuery 1.7.2)。替代jquery live可以工作

有人可以解釋爲什麼.live是唯一可行的功能,爲什麼其他功能不工作(或者如果我對其他功能做錯了)。


$(document).ready(function(){ 
    $(".OpenPopup").bind('click', function(e){ 
     alert('test .OpenPopup'); 
     // do something 
     return false; 
    }); 
    $(".EditIcon").bind('click', function(){ 
     alert('test .EditIcon'); 
     // do something 
     $("#ABC").html('<div class="EditIcon OpenPopup" pwidth="800" pheight="500" ptitle="EditText">click here again</div>'); 
    }); 
}); 


<div id="ABC"><div class="EditIcon OpenPopup" pwidth="800" pheight="500" ptitle="EditText">click here</div></div> 
+2

'.On'是正式替代'.Live' –

+2

閱讀答案jQuery的文檔常見問題解答'why' – charlietfl

+0

我把它用。對工作()。我有錯誤的語法。 –

回答

16
$(document).ready(function(){ 
     $(document.body).on('click', ".OpenPopup", function(e){ 
      alert('test .OpenPopup'); 
      // do something 
      return false; 
     }); 
     $(document.body).on('click', ".EditIcon", function(){ 
      alert('test .EditIcon'); 
      // do something 
      $("#ABC").html('<div class="EditIcon OpenPopup" pwidth="800" pheight="500" ptitle="Edit Text">click here again</div>'); 
     }); 
    }); 
+0

哇從來沒有想過這種方式,我仍然在尋找一些替代方式.live在最新的jquery版本中,是否有任何正式的聲明?謝謝你的代碼片段,我會測試這個 –

+1

但你如何瞄準。被點擊的openpopup? – PixMach

+0

單擊處理程序中的'e.target' - [jQuery event.target doc](https://api.jquery.com/event.target/) –

2

.on()可以使用with or without delegation,以下爲使用授權()的上的示例。

$("#ABC").on('click', ".OpenPopup", function(e){ 

http://jsfiddle.net/BmEZv/1/

+0

這是行不通的。它按預期工作在第一次點擊上,但在第二次點擊時,它只使用.on()註冊第一次提醒。 $(「。EditIcon」)。bind('click',function(){ 沒有被解僱,我也試過用.delegate()。 –

+0

@BrandonOrth你想讓我爲你重寫整個代碼嗎?,只需將第二個綁定更改爲'on()' – Musa

+0

我修改了示例以將.on()添加到.EditIcon click。Works。謝謝 –

0

繼@Dhofca這果然奏效。我只是展示了一個我用'this'關鍵字嘗試過的例子。

$(document.body).on('click', ".query-result table tr", function() { 
    var el = $(this); 
    el.closest('table').find('tr').removeClass('dotted'); 
    el.addClass('dotted'); 
});