2017-05-09 59 views
0

我想在我的代碼中使用Bootstrap動態表。下面是HTML代碼:Bootstrap動態表不工作

<button type="button" id="show">Change Content</button> 
<div class="table-responsive"> 
    <table id="tabl" class="table table-condensed"></table>    
</div> 

而且JS代碼:

$(document).ready(function() { 

$('.deliverable-infos').hide(); 
$('.dropdown-deliverable').on('click', function(e) { 
    console.log("dropdown toggled!"); 
    e.preventDefault(); 
    e.stopPropagation(); 
    //get targeted element via data-for attribute 
    var dataFor = $(this).data('for'); 
    var idFor = $(dataFor); 
    idFor.slideToggle(); 
}); 

}); 
$('#show').click(function(){ 
    var table="<thead><tr><th>Deliverable</th><th>Description</th><th>Ending on</th></tr></thead>"; 
       table+="<tr class='clickable warning dropdown-deliverable' data-for='#details_1'><td>uranium</td><td>magic potion</td><td>April 23, 2014</td></tr><tr style='padding:0'><td style='padding:0px'></td><td colspan=2 style='padding:0px;'><div class='deliverable-infos' id='details_1'><table class='table table-condensed table-user-content' id='hidden_table_1'><tr><td>نام کالا :</td><td class='right-col'>April 22, 2013</td></tr><tr><td>قیمت :</td><td class='right-col'>500 h</td></tr><tr><td>تخفیف :</td><td class='right-col'>3000 €</td></tr></table></div></td><td style='padding:0'></td><td style='padding:0'></td></tr><tr class='clickable warning dropdown-deliverable' data-for='#details_2'><td>detonator</td><td>magic wand</td><td>April 23, 2014</td></tr><tr style='padding:0'><td style='padding:0'></td><td colspan=2 style='padding:0'><div class='deliverable-infos' id='details_2'><table class='table table-condensed table-user-content' id='hidden_table_2'><tbody><tr><td>Started:</td><td class='right-col'>April 22, 2013</td></tr><tr><td>Load:</td><td class='right-col'>20 h</td></tr><tr><td>Fare:</td><td class='right-col'>200 €</td></tr></tbody></table></div></td><td style='padding:100px'></td><td style='padding:100px'></td></tr>"; 
       document.getElementById("tabl").innerHTML = table; 
}); 

但是當我運行它,它讓我所有的表和動態側不工作。

+0

因爲這是JS選擇器和事件偵聽器的一個重要課題的給予好評。 –

回答

0

當你用你的網頁上動態內容,您需要使用下面的方法來添加事件偵聽器:

$(document).on('click', '.dropdown-deliverable', function(e) { 
}); 

代替:

$('.dropdown-deliverable').on('click', function(e) { 

}); 

那麼它將工作。

瞭解更多關於動態事件監聽器在這裏:http://api.jquery.com/on/#direct-and-delegated-events

UPDATE 使用:

$(document).on('click', '.dropdown-deliverable', function(e) { 
}); 

$(document)可以通過在頁面(IE)的任何靜態元素取代不產生動態。

例如,你可以使用表ID =「TABL」,因爲它是不是在頁面上dymanic,所以你的代碼變成:

$('#tabl').on('click', '.dropdown-deliverable', function(e) { 
}); 
+0

謝謝:)它的工作 – mjvoodoo

+0

@ mjvoodoo偉大..平我,如果你有任何進一步的問題。 –

+0

抱歉,但似乎我有一個問題:)它顯示了一行中的所有子數據。我添加了一幅應該是什麼以及現在是什麼的圖片。 – mjvoodoo