2014-05-20 19 views
0

在加載頁面時,我顯示一個動態手風琴,並點擊手風琴元素,我創建div id動態並附加數據給他們。如何註冊點擊事件的div的ID的動態生成

我的要求是,當手風琴內的div被選中時,我想要得到那個選定的文本。

如果我以這種方式註冊,即使選擇了手風琴,它也會啓動。

$('#div').click(function() 
    { 
     alert("click"); 
}); 

我也嘗試過,但在身上載入它給予未定義。

$("#"+selectedeleemnt+"").click(function() 
{ 

}); 

這是我的完整的程序

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
pageEncoding="ISO-8859-1" import="java.util.*, com.as400samplecode.util.*"%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>jQuery Accordion</title> 
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    <script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> 


    <script type="text/javascript"> 
var xmldocu = '<categories><category id="2" name="Pepsi" ><products><product id="858" name="7UP" price="24.4900" /><product id="860" name="Aquafina" price="24.4900" /></products></category><category id="4" name="Coke" ><products><product id="811" name="ThumpsUp" price="24.4900" /><product id="813" name="Maaza" price="24.4900" /></products></category></categories>' ; 
      $(document).ready(
      function() { 
       $("#accordion").accordion({ header: "h3",   
        autoheight: false, 
        active: false, 
        alwaysOpen: false, 
        fillspace: false, 
        collapsible: true, 
       }); 

$("#accordion").accordion({ 
activate: function(event, ui) { 
var selectedeleemnt = ui.newHeader.text(); 
if(selectedeleemnt=="CoolDrinks") 
{ 
$(xmldocu).find("category").each(function() { 
var categories = $(this).attr('name'); 
    var str= ''; 
var UL = $("<ul></ul>"); 
str += '<li>' + categories + '</li>'; 
UL.append(str); 
$("#"+selectedeleemnt+"").append(UL); 

}); 
} 
} 
}); 


}); 


    </script> 

</head> 
<body> 

    <div style="width: 468px;"> 
     <div id="accordion"> 
<% 
     ArrayList<String> list = new ArrayList<String>(); 
     list.add("CoolDrinks"); 
     list.add("Snacks"); 
     list.add("Other"); 
     %> 

<% 
     for(String item : list) 
     { 
      %> 
      <h3><a href="#"><%=item%></a></h3> 
      <div> 
       <h4 id="<%=item%>"></h4> 
      </div> 
     <% 
     } 
     %> 
     <% 
     %> 

    </div> 
    </div> 

</body> 
</html> 
+0

你嘗試加載它,它是動態創建之後? – LefterisL

+1

在創建和編寫類選擇器時添加一個類,並在事件中獲取idof單擊div –

+0

http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements –

回答

2

嘗試使用。對()

$("#accordion").on("click", "h4", function() { 
    alert($(this).text()); 
}); 
+1

非常感謝您的工作完美。 – Pawan

相關問題