jQuery .click()不工作?

我按如下方式生成html表中的按钮组,然后我想在单击时调用函数。

$.each(childData, function(key, item) { var packPath = key.replace(/_/g, "/"); //Replace underscore with slash div.innerHTML = div.innerHTML + ''+key+'' + '
'; })

这就是我调用函数但它无法正常工作的方式。

 $(".download").click(function(){ alert(); }); 

上面的代码在哪里错了?

试试这个:

 $(document).on('click', '.download', function(){ // Your Code }); 

将事件委托给静态父级:

 $(div).on("click", ".download", function(){ 

这里div可以是在第一次加载时加载页面时可用的静态父级。 虽然documentbody也可以用来代替div


由于您还没有介绍如何创建div元素,但有一点需要注意,您正在生成无效标记。 因为td元素不能是div的子元素而是tabletr元素。

您需要使用事件委派。

如果您的表的id为“button-table”,则可以创建一个事件处理程序,如下所示:

 $("#button-table").on("click",function(e){ var target = e.target; console.log($(target).attr("data-id")); }); 

你想要这样吗? 我已经给出了添加整个表的代码。检查一下

 function generate_table() { // get the reference for the body var body = document.getElementsByTagName("body")[0]; // creates a  element and a  element var tbl = document.createElement("table"); var tblBody = document.createElement("tbody"); // creating all cells for (var i = 0; i < 2; i++) { // creates a table row var row = document.createElement("tr"); for (var j = 0; j < 2; j++) { // Create a  in the 
element and a text node, make the text // node the contents of the , and put the at // the end of the table row var cell = document.createElement("td"); var cellText = document.createTextNode("cell in row "+i+", column "+j); cell.appendChild(cellText); row.appendChild(cell); } // add the row to the end of the table body tblBody.appendChild(row); } // put the
tbl.appendChild(tblBody); // appends
into body.appendChild(tbl); // sets the border attribute of tbl to 2; tbl.setAttribute("border", "2"); }