简体   繁体   中英

Delete a table row from Json using node and jQuery (No database)

I am trying to figure out how to delete a field from a Json array on click of a delete button. I am quite new at this and can't seem to figure out how to achieve this. Here is what a simple table that pulls the data from a JSON file looked like:

一个简单的表,可从JSON文件中提取数据

Here is the code:

 $(".task_box").on("click", function(evt){ $("#task_table").show(); $.getJSON("db.json", function(data) { $.each(data, function(key,value) { console.log("Get Json data worked"); task = data; var row = $('<tr><td>' + task.box1[0].taskName+ '</td><td>' + task.box1[0].time + '</td><td>' + task.box1[0].location + '</td><td>' + '<button type="button" class="btn btn-warning">Delete</button>') $('#task_table').append(row); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="tasks_list"> <table id="task_table" class="tableStyle" > <tr> <th>Task Name</th> <th>Time</th> <th>Location</th> </tr> </table> </div> </div> </div> 

I need to somehow update and delete table content with node, can anyone help me achieve this? Also is there a better way to fetch my array? This does not run too well for me.

I have been learning Node for about less than a week and I really can't figure this out.

Instead of onClick for each button you can just set each button with a class say "delete", bind the event to the table and delete the closest tr using jquery.

First change:

'<button type="button" class="btn btn-warning">Delete</button>'

to

'<button type="button" class="btn btn-warning delete">Delete</button>'

and then bind it to the table

$('table').on('click','tr a.delete',function(e){
  e.preventDefault();
  $(this).closest('tr').remove();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM