2014-01-29 100 views
0

我試圖創建一個簡單的組合框,但也許jQuery的整合邏輯可能是不正確的,我想知道如果有辦法做到這一點,我可能不會看到一個更合乎邏輯的方式。動態添加元素和處理事件

我有這樣的代碼,填充基於PHP的拉動從MySQL的一個下拉菜單:

​​

這基本上有一個下拉菜單,depnding在選擇的價值,上展開將拉動其他選擇框,是從一個PHP腳本和MySQL查詢

$("#expandBtn").click(function(){ 
     i++; 
     var checkSelect = $("#levelDrop option:selected").val(); 
     if(checkSelect !== "NULL"){ 
      var itemSelected = $("#levelDrop option:selected").val(); 
      alert(itemSelected); 
      $.ajax({ url: '****/phpFunctions/actions/getSelectList.php', 
      data: {w: itemSelected, x: i}, 
      type: 'GET', 
      success: function(output) { 
                  alert(output); 
       $("#expandBtn").remove(); 
       $("#levelsRow").append(output); 

              } 
     }); 
     }//end if check select 
     //send the variable to getFeatures list and have it reuturn in the divison and print the value in application. 
    }); 

php的輸出端的查詢結果具有完全相同的字段和字段名。這應該適用於X數量的選擇和擴展,唯一的問題是該按鈕在第二次輸入後將不起作用。

+0

看到這些職位信息如何使用委派事件處理動態地添加元素:http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-事件後裝動態-HT/8752376#8752376和http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-處理程序,是-CRE/9814409#9814409。 – jfriend00

回答

1

對於動態生成的元素,使用事件委派使用.on()像下面

$(document).on('click', '#expandBtn', function(){ 

,而不是

$("#expandBtn").click(function(){ 
+0

謝謝你,這是否在$(document).ready函數中,還是將它分開? – user1058359

+0

@ user1058359裏面的文件就緒功能。 – Krishna

+0

嗨,所以點擊開始響應按鈕;然而,它繼續引用第一個選擇(我假設,因爲ID是相同的,這些是原來的)有沒有辦法繼續擴展,但讓JQuery動態引用新創建的選擇框的ID? – user1058359

0

我會建議使用一個href的。 你可以在你的href中調用這個函數。

因此,例如:

<?php 
echo "<a href="javascript:functionToExpand(" . $row["ID"] . ");" class='your_style_class'>Expand</a>"; 
?> 

在JavaScript中,你可以這樣做:(這是腳本標籤內)

<script type="text/javascript"> 
function functionToExpand(id_of_row) { 
    //Do what you want to do 
    //Can be same implementation of $("").click(function() { //this code }); 
} 
</script> 

現在你不需要jQuery來綁定事件!

相關問題