首页 > 解决方案 > 为什么 $(this).attr("id") 在使用 javascript 更改旧属性后获取旧属性

问题描述

我有一个奇怪的问题,所以在删除一行后更改了所有表行的 id 之后。
这是我的代码的一部分:

$(document).on("click",".fa-trash-alt",function(){
    console.log($(this).attr("id"))
    let index = parseInt($(this).attr("id"))
    globalFunctions.removeFromChoosedList(index)
    $('tr#'+index).remove()
    let rows = $(".choosed-table-data tr")

   $.each(rows,function(index,value){
     $(value).attr("id",index)
   })
  })

问题是,在此操作之后,当我单击应该具有新 id 的行时,console.log($(this).attr("id"))尽管检查器上的 id 已更改,但旧 id 仍会出现

标签: javascriptattributesattr

解决方案


很难举个例子,因为没有 HTML 可以关联 js 代码。如果您想要更相关的示例,请编辑问题以包含 html。

$(".clicked-elm").click((e) => {

    // removes the clicked element
    e.target.remove();
    
    // if you want to remove the children instead do
    e.target.children.forEach(elm => elm.remove());
    
    // not sure what chosen data table is, 
    // but this example should change the id's of each element with that class,
    // unless $() only picks first element. 
    // If so, change it to $$() and it should select all matches.
    $(".choosed-table-data tr").forEach((elm, i) => $(elm).attr("id", i));
});


推荐阅读