2016-10-03 59 views
0

我有一個頁面有2個選項卡。每個選項卡都加載了自己的DataTable和工具欄控件。根據哪個選項卡處於活動狀態,我會動態地添加相應的工具欄(使用自定義按鈕)。但是onclick事件不會觸發選項卡中動態添加的元素。下面是代碼我使用的控件添加到不同的標籤:點擊事件不發射動態添加按鈕內部選項卡

$("#tabs").tabs({ 
     active: 0,//Tab no.2 "Sha-2" by default active on page load, 
     "activate": function(event, ui) { 
      var table = $.fn.dataTable.fnTables(true); 

      if (table.length > 0) { 

       $(table).dataTable().fnAdjustColumnSizing(); 
       var active = $("#tabs").tabs("option", "active"); 
       if(active == 0){ //add toolbar to tab index = 1 
        $("div.toolbar").html(''); 

       } 
       if(active == 1){ //add toolbar to tab index = 1 


        $("div.toolbar").html('<a id= "add-vendor"class="ui-button ui-widget ui-corner-all">ADD VENDOR</a><a id= "create-purchase_order"class="ui-button ui-widget ui-corner-all">CREATE PO</a>'); 

        $("#add-vendor").button().on("click", function() { 
        alert('hello'); 
        }); 

       } 
      } 
     } 
    }); 

的代碼是一個文檔準備function.Could裏面有人幫我捉按鈕的onclick事件?

+0

可以請你在這裏發佈整個工作頁面,看起來你的點擊事件沒有被附加,因爲#add-vendor當時不可用。 – MGA

回答

-1

你需要委派動態添加的按鈕:

$(*ParentOfTheDynamicallyAddedButton*).delegate("DynamicallyAddedButton", "click", function(){ 
    *your function* 
    } 

你可以說你的瀏覽器不知道動態添加元素,因爲它們不是腳本的一部分。它們只存在於DOM中,因此沒有附加腳本。但不要引用我的話,我是一個noob。

+1

.delegate()已被棄用。它被.on()方法取代,因爲jQuery 1.7 –

+0

似乎不適用於他 –

1

它不起作用,因爲您正在將錨標記轉換爲按鈕。如果刪除按鈕方法,然後它工作正常:

$("div.toolbar").html('<a id= "add-vendor"class="ui-button ui-widget ui-corner-all">ADD VENDOR</a><a id= "create-purchase_order"class="ui-button ui-widget ui-corner-all">CREATE PO</a>'); 

    $("#add-vendor").on("click", function() { 
     alert('hello'); 
    }); 

如果你要使用按鈕,然後創建一個按鈕標記,而不是定位標記。

+0

以及我們可以像$(「body」)。on(「click」,「#add-vendor」函數(){ alert('hello'); }); –

1
$(document).on('click', "#add-vendor", function() { 
      alert('hello'); 
    }); 

將做的伎倆,委託事件到文件的動態添加元素。