2013-06-24 94 views
0

我使用的引導

以下是我的代碼,以動態獲取飼料,然後通過編號爲師內追加添加它們在頁面上「飼料」:上動態添加按鈕註冊單擊事件的jQuery

$.ajax({ 
    url: 'http://api.feedzilla.com/v1/categories/'+newsId+'/articles.json', 
    type: 'GET', 
    dataType: 'json', 

    // to execute when successfully got json response 
    success: function(response){ 
     $.each(response.articles, function(){ 
      var feed= "<div class='media well'>"+ 
          "<div class='media-body'>"+ 
           "<h4 class='media-heading'>"+this.title+"</h4>"+ 
           "<h6>"+this.publish_date+"</h6>"+ 
           "<p>"+this.summary+"</p>"+ 
           "<a href='"+this.url+"' target='_blank'>Continue Reading</a>"+ 
          "</div><br><br>"+ 
          "<button class='showinfo btn pull-right' id='info'>Show Info</button>"+ 
         "</div>"; 

      $('#feeds').append(feed); 
     }); 
    }, 

    // to execute when error 
    error: function(jqXHR, textStatus, errorThrown){ 
     alert("Server error!"); 
    }, 

    // execute at last whether success or error 
    complete: function(){ 

    } 
}); 

正如你所看到的,我添加了一個類'showinfo'以及id'info'來動態添加按鈕。

現在,以下是我的事件處理程序:

// SHOW INFO BUTTON CLICK HANDLER 
    $('.showinfo').click(function(){ 
     alert('triggered'); 
    }); 

但它不工作:(!!既不與ID:$( '#信息')點擊()! 如果我不」不要再增加了動態按鈕,它可以完美運行爲什麼會是這樣

+0

的其他一千問題重複... –

+0

id屬性應該是唯一的 – HarryFink

回答

14

使用on():?

$('#feeds').on('click', '.showinfo', function() { 
    alert('triggered'); 
}); 

以上結合任何點擊事件上匹配的任何元素.showinfo裏面的#feeds到指定的回調函數。另外,請注意在綁定時存在應該匹配的元素(在這種情況下爲.showinfo不需要(因此它也適用於動態添加的元素)。

+3

+1,但有點的說明會養活他一輩子;) – Archer

+2

@Archer - 是的。實際上是在添加這個過程。完成。 – techfoobar

+1

@techfoobar謝謝!請給我一輩子,添加一些解釋:D – kunal18

4

您必須爲動態添加的元素執行event delegation

// SHOW INFO BUTTON CLICK HANDLER 
    $('#feeds').on("click",'.showinfo' ,function(){ 
     alert('triggered'); 
    }); 

爲什麼on()工作?

事件處理程序僅綁定到當前選定的元素;它們必須在代碼調用.on()時存在於頁面上。

1

.click適用於現有的物體。如果您的控件要動態添加,請使用.on(或live - 但我已棄用)。它爲動態添加的對象附加事件。

$('.showinfo').on('click', function(){ 
    alert('triggered'); 
});