最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Click event not working in javascript - Stack Overflow

programmeradmin7浏览0评论

I Follow This Article for Impalement CRUD Operation with HTML5 and Javascript.

So that Submit Data to Local Storage and save it.

my problem is Delete and Edit Operation when clicking on delete and edit button Nothing happens.

Javascript

$(function () {
  var operation = "A";
  var selected_index = -1;
  var tbClients = localStorage.getItem("tbClients"); //Retrieve the stored data
  tbClients = JSON.parse(tbClients); //Converts string to object
  if (tbClients === null) //If there is no data, initialize an empty array
    tbClients = [];

  function Add() {
    debugger;
    var Data = {
      ExternalProjects: {
        Name: $('#Name').val(),
        Body: $('#Body').val(),
        Url: $('#Url').val()
      }
    };

    tbClients.push(Data);
    localStorage.setItem("tbClients", JSON.stringify(tbClients));
    alert("The data was saved.");
    List();
    return true;
  }

  function Edit() {
    tbClients[selected_index] = JSON.stringify({
      Name: $('#Name').val(),
      Body: $('#Body').val(),
      Url: $('#Url').val()
    }); //Alter the selected item on the table
    localStorage.setItem("tbClients", JSON.stringify(tbClients));
    operation = "A"; //Return to default value
    return true;
  }

  function List() {

    debugger;
    var div = $('div#ExProjectList');
    div.html("");
    var cli = tbClients;
    for (var i = 0; i < cli.length; i++) {
      debugger;
      div.append(
        '<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">' +
        '<div class="d-flex w-100 justify-content-between">' +
        ' <h5 class="mb-1">' + cli[i].ExternalProjects.Name + '</h5>' +
        '  <small>' +
        '<a id="btnDelete"  alt="Delete' + i + '"><i class="fa fa-trash" style="cursor: pointer" ></i></a>' +
        '<a id="btnEdit" alt="Edite' + i + '"><i class="fa fa-pencil" style="cursor: pointer"></i></a>'
        + '</small>' +
        ' </div>' +
        '<p class="mb-1">' + cli[i].ExternalProjects.Body + '</p>' +
        '<small>' + cli[i].ExternalProjects.Url + '</small>' +
        '</div>'
      );
    }
  }

  function Delete() {
    tbClients.splice(selected_index, 1);
    localStorage.setItem("tbClients", JSON.stringify(tbClients));
  } 


  $('#btnDelete').bind('click', function() {
    selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
    Delete();
    List();
  });

  $("#btnEdit").bind("click", function() {
    operation = "E";
    selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
    var cli = JSON.parse(tbClients[selected_index]);
    $("#Name").val(cli.ExternalProjects.Name);
    $("#Body").val(cli.ExternalProjects.Body);
    $("#Url").val(cli.ExternalProjects.Url);
  });




  $("#AddExternalProject").click(function () {
    if (operation === "A"){
      return Add();
    }
    else{
      return Edit();
    }
  });
});

I Follow This Article for Impalement CRUD Operation with HTML5 and Javascript.

So that Submit Data to Local Storage and save it.

my problem is Delete and Edit Operation when clicking on delete and edit button Nothing happens.

Javascript

$(function () {
  var operation = "A";
  var selected_index = -1;
  var tbClients = localStorage.getItem("tbClients"); //Retrieve the stored data
  tbClients = JSON.parse(tbClients); //Converts string to object
  if (tbClients === null) //If there is no data, initialize an empty array
    tbClients = [];

  function Add() {
    debugger;
    var Data = {
      ExternalProjects: {
        Name: $('#Name').val(),
        Body: $('#Body').val(),
        Url: $('#Url').val()
      }
    };

    tbClients.push(Data);
    localStorage.setItem("tbClients", JSON.stringify(tbClients));
    alert("The data was saved.");
    List();
    return true;
  }

  function Edit() {
    tbClients[selected_index] = JSON.stringify({
      Name: $('#Name').val(),
      Body: $('#Body').val(),
      Url: $('#Url').val()
    }); //Alter the selected item on the table
    localStorage.setItem("tbClients", JSON.stringify(tbClients));
    operation = "A"; //Return to default value
    return true;
  }

  function List() {

    debugger;
    var div = $('div#ExProjectList');
    div.html("");
    var cli = tbClients;
    for (var i = 0; i < cli.length; i++) {
      debugger;
      div.append(
        '<div href="#" class="list-group-item list-group-item-action flex-column align-items-start">' +
        '<div class="d-flex w-100 justify-content-between">' +
        ' <h5 class="mb-1">' + cli[i].ExternalProjects.Name + '</h5>' +
        '  <small>' +
        '<a id="btnDelete"  alt="Delete' + i + '"><i class="fa fa-trash" style="cursor: pointer" ></i></a>' +
        '<a id="btnEdit" alt="Edite' + i + '"><i class="fa fa-pencil" style="cursor: pointer"></i></a>'
        + '</small>' +
        ' </div>' +
        '<p class="mb-1">' + cli[i].ExternalProjects.Body + '</p>' +
        '<small>' + cli[i].ExternalProjects.Url + '</small>' +
        '</div>'
      );
    }
  }

  function Delete() {
    tbClients.splice(selected_index, 1);
    localStorage.setItem("tbClients", JSON.stringify(tbClients));
  } 


  $('#btnDelete').bind('click', function() {
    selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
    Delete();
    List();
  });

  $("#btnEdit").bind("click", function() {
    operation = "E";
    selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
    var cli = JSON.parse(tbClients[selected_index]);
    $("#Name").val(cli.ExternalProjects.Name);
    $("#Body").val(cli.ExternalProjects.Body);
    $("#Url").val(cli.ExternalProjects.Url);
  });




  $("#AddExternalProject").click(function () {
    if (operation === "A"){
      return Add();
    }
    else{
      return Edit();
    }
  });
});
Share Improve this question edited Jan 20, 2017 at 17:45 mhodges 11.1k2 gold badges31 silver badges48 bronze badges asked Jan 20, 2017 at 17:35 Soheil AlizadehSoheil Alizadeh 3,06611 gold badges32 silver badges57 bronze badges 11
  • 2 My guess is that your page loads and your jQuery runs before those items are loaded into the DOM. – Forklift Commented Jan 20, 2017 at 17:38
  • Any messages in your developer console? – Steven B. Commented Jan 20, 2017 at 17:39
  • 4 Edit & Delete buttons are being added dynamically from the List() function. You need to use a delegate selector in order to bind click handlers to them. It would look like so: $("#ExProjectList").on("click", "#btnDelete", function () {...}); and same with #btnEdit. Here are the docs for delegate selectors so you can read more about them: learn.jquery./events/event-delegation – mhodges Commented Jan 20, 2017 at 17:42
  • It's probably also worth mentioning that you are adding the HTML in your List() function within a loop, yet the <a> tags you are adding have IDs on them - meaning that there is the possibility of duplicate IDs, which leads to bugs very quickly. It would be best that you use classes or data-attributes to identify your btnDelete and btnEdit elements. – mhodges Commented Jan 20, 2017 at 17:48
  • 1 @mhodges Thank Fixed – Soheil Alizadeh Commented Jan 20, 2017 at 17:58
 |  Show 6 more ments

2 Answers 2

Reset to default 4

You are creating the HTML dynamically, but not attaching the event to the element.

Instead of using:

$('#btnDelete').bind('click', function() {
    selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
    Delete();
    List();
});


$("#btnEdit").bind("click", function() {
    operation = "E";
    selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
    var cli = JSON.parse(tbClients[selected_index]);
    $("#Name").val(cli.ExternalProjects.Name);
    $("#Body").val(cli.ExternalProjects.Body);
    $("#Url").val(cli.ExternalProjects.Url);
});

Use event delegation:

$("#ExProjectList").on("click", "#btnDelete", function() {

    selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
    Delete();
    List();
});

$("#ExProjectList").on("click", "#btnEdit", function() {
    operation = "E";
    selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
    var cli = JSON.parse(tbClients[selected_index]);
    $("#Name").val(cli.ExternalProjects.Name);
    $("#Body").val(cli.ExternalProjects.Body);
    $("#Url").val(cli.ExternalProjects.Url);
});

If you are binding any event to any html element, always bind inside

$(document).ready(function(){
//code here
});

Because if you add the script earlier before Dom Content is ready, in self calling function then those elements will not be available to bind the events.

发布评论

评论列表(0)

  1. 暂无评论