2011-10-06 63 views
3

我試圖在HTML頁面中添加& DELETE按鈕以刪除或添加圖像代碼。 DELETE按鈕將刪除按鈕之前的第一個圖像。 ADD按鈕將向HTML頁面插入一個新圖像,並在圖像上插入刪除按鈕。jQuery中的DOM更改後點擊事件不會觸發

代碼工作正常:單擊DELETE按鈕時刪除圖像,單擊ADD按鈕時插入圖像。問題是:單擊ADD按鈕後插入的刪除按鈕不起作用。所以如果你點擊ADD按鈕,然後點擊DELETE按鈕,圖像將不會隱藏;點擊事件不會觸發。

下面是代碼:

<html> 
    <head> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 
    <script type="text/javascript"> 

     $(document).ready(function(){ 
      $('.img-post input').after('<button type="button" >Delete</button>'); 

      $(".img-post button").click(function() { 
        $(this).prev().prev().remove(); 
        $(this).prev().remove(); 
        $(this).remove(); 
      }); 

      $(".add-img button").click(function() { 
        $('<img src="image3.jpg" /><input type="hidden" name="allimages[]" value="image3.jpg" /><button type="button" >Delete</button><br />').appendTo('.img-post'); 
      }); 

     }); 


     </script> 
    </head> 
    <body> 
      <div class="img-post"> 
       <img src="image1.jpg" /><input type="hidden" name="allimages[]" value="image1.jpg" /><br /> 
       <img src="image2.jpg" /><input type="hidden" name="allimages[]" value="image2.jpg" /><br /> 
      </div> 

      <div class="add-img"> 
       <button type="button" >Add image</button> 
      </div> 

    </body> 
</html> 

回答

9

綁定使用live(),而不是click()事件處理程序的按鈕的單擊事件:

$(".img-post button").live('click', function() { 
    $(this).prev().prev().remove(); 
    $(this).prev().remove(); 
    $(this).remove(); 
}); 

這將確保您的選擇匹配的所有按鈕它們是在初始DOM負載之後添加也會觸發相同的功能。

http://api.jquery.com/live/

+0

請注意,此功能從jQuery 1.9中刪除 – 2015-04-03 15:15:05

3

使用live代替:

$(".img-post button").live('click', function() { ... 
3

你必須改變你的.click(fn)處理程序.live("click", fn)。您的.click()處理程序只能處理document.ready時頁面中的元素。您動態添加的元素不存在,因此他們沒有點擊處理程序。

.live(),在另一方面,着眼於在頂級點擊,然後對它們進行檢查,看看他們是否被點擊的匹配對象上,將與動態添加到頁面初始化代碼運行之後的對象。 .live()只適用於某些事件(發生泡泡的事件),但點擊就是其中的一種。

$(document).ready(function(){ 
     $('.img-post input').after('<button type="button" >Delete</button>'); 

     $(".img-post button").live("click", function() { 
       $(this).prev().prev().remove(); 
       $(this).prev().remove(); 
       $(this).remove(); 
     }); 

     $(".add-img button").live("click", function() { 
       $('<img src="image3.jpg" /><input type="hidden" name="allimages[]" value="image3.jpg" /><button type="button" >Delete</button><br />').appendTo('.img-post'); 
     }); 

    }); 
3

嘗試使用jQuery live函數。這會將點擊處理程序綁定到與選擇器匹配的元素,即使它們在頁面初始加載時(如您的示例中的情況)在DOM中不存在時也是如此。