开发者

jQuery: Can't use the "find" method twice on a single object

I'm currently trying to use the jquery "find" method on an object twice but it isn't letting me do it, only the first instance of "find" is working. Here is the code that I would like to run...

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

The above code works just fine except for the last "find" method, it isn't removing the elements with a ".delete_phone" class.

However, if I change the code to look like this...

$("#phone_numbers > p:first-child").clone(true).insertBefore("#ph开发者_如何学Cone_numbers > span:last-child").find('.delete_phone').remove();

It does remove the elements with a ".delete_phone" class. I assume this is because I can't use the "find" method twice in a row, but I'm not sure.

Does anyone know what's going on or if there is a way around this problem?

Thanks!


You need a .end() to hop back in the chain (so you're not looking inside the previous .find() results), like this:

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

Broken down view:

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


It looks like you are trying to cram a lot of requests into one line when you don't really need to. I'm not exactly sure what you are aiming to do, but I would manage it more like this.

Instead let's break it down into three simple requests:

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'

Not sure what you are trying to do for the val() part as you are not storing the value in a variable, neither are you changing the value.

If you need more help message back.

W.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜