簡體   English   中英

jQuery函數不點擊點擊

[英]jquery function not calling on click

我有一個像這樣的功能:

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甚至不會觸發。 我在這里做錯了什么?

試試這個

$(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);
          }

    });

希望這會幫助你。

如操作規范下的注釋所建議,(感謝@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);
      }

});

解決問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM