jQuery .click()不工作?

时间:2017-01-06 04:47:46

标签: javascript jquery click

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

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

    div.innerHTML = div.innerHTML + '<td>'+key+'</td>'
                + '<td><button type="button" data-id="'+key+'" class="download btn btn-success btn-xs">Originals</li></td></div>'; 

}) 

这就是我调用函数的方法,但它不起作用。

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

上述代码中的错误在哪里?

4 个答案:

答案 0 :(得分:5)

试试这个:

{{1}}

答案 1 :(得分:1)

将事件委托给静态父级:

document

此处body可以是在第一次加载时加载页面时可用的静态父级。虽然也可以使用divdiv代替td

由于您尚未介绍如何创建div元素,但必须注意一件事是您生成了无效的标记。由于table元素不能是tr$(document).on('click', '.download', function(){ // Your Code }); 的{​​{1}}的孩子。

答案 2 :(得分:0)

您需要使用事件委派。

如果你的表的id为“button-table”,你可以像这样创建一个事件处理程序:

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

答案 3 :(得分:0)

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

&#13;
&#13;
function generate_table() {
  // get the reference for the body
  var body = document.getElementsByTagName("body")[0];
 
  // creates a <table> element and a <tbody> 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 <td> element and a text node, make the text
      // node the contents of the <td>, and put the <td> 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 <tbody> in the <table>
  tbl.appendChild(tblBody);
  // appends <table> into <body>
  body.appendChild(tbl);
  // sets the border attribute of tbl to 2;
  tbl.setAttribute("border", "2");
}
&#13;
<input type="button" value="Generate a table." onclick="generate_table()">
&#13;
&#13;
&#13;