簡體   English   中英

jQuery:不能在單個對象上使用“find”方法兩次

[英]jQuery: Can't use the “find” method twice on a single object

我目前正在嘗試在對象上使用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();

上面的代碼工作正常,除了最后一個“查找”方法,它不是刪除帶有“.delete_phone”類的元素。

但是,如果我將代碼更改為這樣......

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

它確實刪除了帶有“.delete_phone”類的元素。 我認為這是因為我不能連續兩次使用“find”方法,但我不確定。

有誰知道發生了什么,或者是否有辦法解決這個問題?

謝謝!

你需要一個.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();

細分視圖:

$("#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

看起來你正在嘗試將很多請求塞進一行,當你真的不需要時。 我不確定你的目標是什么,但我會更像這樣管理它。

相反,讓我們將其分解為三個簡單的請求:

var numbers = $("#phone_numbers > p:first-child");//grab the data you want
numbers.insertBefore("#phone_numbers > span:last-child");//insert it where you want
$("#phone_numbers .delete_phone').remove();//remove numbers with class 'delete_phone'

不確定你要為val()部分做什么,因為你沒有將值存儲在變量中,也沒有更改值。

如果您需要更多幫助消息。

W.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM