2011-10-25 133 views
0

我有一個從MySQL數據庫中獲取的JSON生成數據的列表。我現在想要做的是,當點擊列表中的任何項目時,它將被添加到我的表單的隱藏輸入中,但問題是,如果我這樣做:jQuery click()不能與JSON一起工作

$(".buttonZvrst").click(function(){ 
alert("this is a test"); 
}); 

什麼都不會發生。如果我選擇了不在JSON生成列表中的任何其他元素,它將起作用。它不工作,因爲它是在以後生成的?我需要幫助!這裏是我的getZvrsti函數,其中JSON是。

function getZvrsti(id) { 
      // Save the request to our requests object 
      request[id] = $.getJSON('test.php?parent='+id, function(data) { 
       var html = ""; 
       $.each(data, function(id, name) { 
        if(name['id'] in izbrani){ 
         if(izbrani[name['id']] == true){ 
          html += '<li id="drugaZvrst" class="izbran"><a class="buttonZvrst" href="#" id="'+name['id']+'">'+name['name']+'</a></li>'; 
         } 
         else{ 
          html += '<li id="drugaZvrst"><a class="buttonZvrst" href="#" id="'+name['id']+'">'+name['name']+'</a></li>'; 
         } 
        } 
        else 
        { 
         izbrani[name['id']] = false 
         html += '<li id="drugaZvrst"><a class="buttonZvrst" href="#" id="'+name['id']+'">'+name['name']+'</a></li>'; 
        } 


       }); 
       // Append the list items and then fade in 
       listUl.append(html); 
       druga.show(400); 
       // We no longer have a request going, so let's delete it 
       request = false; 
      }); 
     } 
+1

我發誓這是一個天問幾次。 – zzzzBov

回答

8

您正在使用.click,它在腳本執行過程中爲可用元素綁定了一次。對於動態的元素,你需要.live了jQuery文檔查找.live()

.live:附上處理該事件對於當前選擇現在和將來匹配這,所有的元素。

+0

您應該使用delegate()而不是live()。這是首選的方法。 http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/ – Raghav

1

您需要爲DOM .live將使DOM被初始化.bind之後不會創建活動連接的初始加載後附的元素做.live。

$(".buttonZvrst").live("click", function(e){ 
    alert("this is a test"); 
}); 
0

試圖拋出該代碼回調函數裏面在最後這樣:

  // Append the list items and then fade in 
      listUl.append(html); 
      druga.show(400); 
      // We no longer have a request going, so let's delete it 
      request = false; 

      $(".buttonZvrst").click(function(){ 
       alert("this is a test"); 
      }); 

     }); 
    }