Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - remove appended data with button click id by id

I append a dynamic button and want when I click button Related data will be remove

async function DataShow()
{
for (i = 0; i < localStorage.length; i++)
     {
      x = localStorage.key(i);
      if (x !='debugbar-time-new' && x !='debugbar-time' && x!='__mycart')
      {
        item = await JSON.parse(localStorage.getItem(x))
        $("#table_data").append('<tr> <td>'+item['_id']+'</td> <td>'+item['title']+'</td><td><button class="btn btn-primary remove" value="'+item['_id']+'">remove</button></td></tr>')
      }
    }
} 

there is my remove functionality

$( "#table_data" ).on('click','.remove',function(){
var item_id = $('#table_data button').val()
window.localStorage.removeItem(item_id);
  });

Problem is when I click button Button always fetch last element id I also see with inspect element all button have it's own id I also try $('this').val() but it not working

question from:https://stackoverflow.com/questions/65870076/remove-appended-data-with-button-click-id-by-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the this keyword within the event handler to refer to the element which raised the event. In your case you can use this to get the value property:

$("#table_data").on('click', '.remove', function() {
  var item_id = this.value;
  window.localStorage.removeItem(item_id);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...