【问题标题】:Why $(this).attr("id") get the old attribute after change it with javascript为什么 $(this).attr("id") 在使用 javascript 更改旧属性后获取旧属性
【发布时间】:2021-07-07 21:36:42
【问题描述】:

我有一个奇怪的问题,所以在删除一行后更改了所有表行的 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 的行时,尽管在检查器上更改了 id,但旧 id 仍显示为 console.log($(this).attr("id"))

【问题讨论】:

    标签: javascript attributes attr


    【解决方案1】:

    很难举个例子,因为没有 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));
    });
    
    

    【讨论】:

    • 感谢您的澄清,显然您的注释是正确的,我认为我的问题是,但事实并非如此。
    【解决方案2】:

    @Invizi 感谢您的澄清,显然您的说明是正确的,我认为我的问题很清楚,但事实并非如此。 无论如何,我发现了我犯错的地方,如您所见,我想获取该行的“id”(tr),它是按钮的父级(“.trash-alt”),但我所做的是: $(this).attr("id") 我应该在哪里这样做:
    $(this).parentElement.parentElement.id 穿过父母直到我到达 意思是:=>=> 我觉得我很白痴XD 最后这是我的固定代码

      $(document).on("click",".fa-trash-alt",function(e){
        let parent = e.target.parentElement.parentElement
        let index = parent.id
        globalFunctions.removeFromChoosedList(index)
        parent.remove()
        let rows = $(".choosed-table-data tr")
    
       $.each(rows,function(index,value){
         $(value).attr("id",index)
       })
      })
    

    【讨论】:

      猜你喜欢
      • 2015-11-19
      • 2013-12-22
      • 1970-01-01
      • 2015-02-25
      • 2015-04-16
      • 2015-07-19
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      相关资源
      最近更新 更多