jquery函数没有调用click

时间:2016-08-05 04:50:00

标签: javascript jquery

我有这样的功能:

last_value = null;
$('td').click(function(e) {
  console.log($(e.target).attr("id"));
  if ($(e.target).is("td")) {
    var the_form = $("#edit-form").detach();
    if (last_value) {
      $("#" + last_value.attr("id")).replaceWith(last_value);
    }

    last_value = $(e.target).clone();
    $(the_form).removeClass("hidden");
    var the_input = $(the_form).find("input.form-control");
    $(the_input).attr("name", $(e.target).attr("id"));
    $(the_input).attr("placeholder", $(e.target).text());
    $(e.target).css('padding-top', 1);
    $(e.target).css('padding-bottom', 1);
    $(e.target).text("");
    $(e.target).append(the_form);
  }
});

这应该采用表格单元格,并生成一个填充了单元格内容的内联表单,并替换它。此外,还添加了代码,以便在单击其他单元格时,内容将恢复为原始值。但是,我遇到的问题是这样的:假设我单击一个单元格,A。表单应该是这样的。然后假设我点击了单元格B.然后表格"移动"到该单元格,单元格A中的内容恢复为原始值。现在假设我再次单击单元格A.在这种情况下,不仅表格没有出现,它仍然留在单元格B中。事实上,console.log甚至没有发射。我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

试试这个

$(document).find('td').on('click',function(e){

           e.preventDefault();
           console.log($(e.target).attr("id"));
           if ($(e.target).is("td")) {
                var the_form = $("#edit-form").detach();
                if (last_value) {
                    $("#" + last_value.attr("id")).replaceWith(last_value);
                }

                last_value = $(e.target).clone();
                $(the_form).removeClass("hidden");
                var the_input = $(the_form).find("input.form-control");
                $(the_input).attr("name", $(e.target).attr("id"));
                $(the_input).attr("placeholder", $(e.target).text());
                $(e.target).css('padding-top', 1);
                $(e.target).css('padding-bottom', 1);
                $(e.target).text("");
                $(e.target).append(the_form);
          }

    });

希望这会对你有所帮助。

答案 1 :(得分:0)

正如OP的评论中所建议的那样(感谢@Mohammad Akbari),将代码更改为

$('table').on('click', 'td', function(e){
       console.log($(e.target).attr("id"));
       if ($(e.target).is("td")) {
            var the_form = $("#edit-form").detach();
            if (last_value) {
                $("#" + last_value.attr("id")).replaceWith(last_value);
            }

            last_value = $(e.target).clone();
            $(the_form).removeClass("hidden");
            var the_input = $(the_form).find("input.form-control");
            $(the_input).attr("name", $(e.target).attr("id"));
            $(the_input).attr("placeholder", $(e.target).text());
            $(e.target).css('padding-top', 1);
            $(e.target).css('padding-bottom', 1);
            $(e.target).text("");
            $(e.target).append(the_form);
      }

});

解决了这个问题。

相关问题