jQuery:不能在单个对象上使用"find"方法两次

lew*_*qic 4 javascript jquery

我目前正在尝试在对象上使用jquery"find"方法两次,但它不允许我这样做,只有"find"的第一个实例正在工作.这是我想要运行的代码......

$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.phone_type, .phone_number, .user_phones_id').val('').find('.delete_phone').remove();
Run Code Online (Sandbox Code Playgroud)

上面的代码工作正常,除了最后一个"查找"方法,它不是删除带有".delete_phone"类的元素.

但是,如果我将代码更改为这样......

$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.delete_phone').remove();
Run Code Online (Sandbox Code Playgroud)

它确实删除了带有".delete_phone"类的元素.我认为这是因为我不能连续两次使用"find"方法,但我不确定.

有谁知道发生了什么,或者是否有办法解决这个问题?

谢谢!

Nic*_*ver 10

你需要一个.end()跳回到链中(所以你没有查看以前的.find()结果),如下所示:

$("#phone_numbers > p:first-child").clone(true).insertBefore("#phone_numbers > span:last-child").find('.phone_type, .phone_number, .user_phones_id').val('').end().find('.delete_phone').remove();
Run Code Online (Sandbox Code Playgroud)

细分视图:

$("#phone_numbers > p:first-child").clone(true)
  .insertBefore("#phone_numbers > span:last-child")
  .find('.phone_type, .phone_number, .user_phones_id') //look in the cloned <p>
  .val('')                                             //empty those inputs
  .end()                                               //hope back to the <p>
  .find('.delete_phone')                               //look in the clone <p>
  .remove();                                           //remove those elements
Run Code Online (Sandbox Code Playgroud)